Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitf539571

Browse files
committed
提供JavaScript版本的《把二叉搜索树转换为累加树》
1 parent50ed227 commitf539571

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

‎problems/0538.把二叉搜索树转换为累加树.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,70 @@ func RightMLeft(root *TreeNode,sum *int) *TreeNode {
239239
}
240240
```
241241
242+
JavaScript版本
243+
244+
> 递归
245+
246+
```javascript
247+
/**
248+
* Definition for a binary tree node.
249+
* function TreeNode(val, left, right) {
250+
* this.val = (val===undefined ? 0 : val)
251+
* this.left = (left===undefined ? null : left)
252+
* this.right = (right===undefined ? null : right)
253+
* }
254+
*/
255+
/**
256+
* @param {TreeNode} root
257+
* @return {TreeNode}
258+
*/
259+
var convertBST = function(root) {
260+
let pre = 0;
261+
const ReverseInOrder = (cur) => {
262+
if(cur) {
263+
ReverseInOrder(cur.right);
264+
cur.val += pre;
265+
pre = cur.val;
266+
ReverseInOrder(cur.left);
267+
}
268+
}
269+
ReverseInOrder(root);
270+
return root;
271+
};
272+
```
242273

274+
>迭代
275+
276+
```javascript
277+
/**
278+
* Definition for a binary tree node.
279+
* function TreeNode(val, left, right) {
280+
* this.val = (val===undefined ? 0 : val)
281+
* this.left = (left===undefined ? null : left)
282+
* this.right = (right===undefined ? null : right)
283+
* }
284+
*/
285+
/**
286+
*@param{TreeNode}root
287+
*@return{TreeNode}
288+
*/
289+
varconvertBST=function (root) {
290+
let pre=0;
291+
let cur= root;
292+
let stack= [];
293+
while (cur!==null||stack.length!==0) {
294+
while (cur!==null) {
295+
stack.push(cur);
296+
cur=cur.right;
297+
}
298+
cur=stack.pop();
299+
cur.val+= pre;
300+
pre=cur.val;
301+
cur=cur.left;
302+
}
303+
return root;
304+
};
305+
```
243306

244307
-----------------------
245308
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp