提供JavaScript版本的《把二叉搜索树转换为累加树》

This commit is contained in:
kok-s0s
2021-07-04 18:22:39 +08:00
parent 50ed227f55
commit f539571a65

View File

@ -239,7 +239,70 @@ func RightMLeft(root *TreeNode,sum *int) *TreeNode {
} }
``` ```
JavaScript版本
> 递归
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var convertBST = function(root) {
let pre = 0;
const ReverseInOrder = (cur) => {
if(cur) {
ReverseInOrder(cur.right);
cur.val += pre;
pre = cur.val;
ReverseInOrder(cur.left);
}
}
ReverseInOrder(root);
return root;
};
```
> 迭代
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var convertBST = function (root) {
let pre = 0;
let cur = root;
let stack = [];
while (cur !== null || stack.length !== 0) {
while (cur !== null) {
stack.push(cur);
cur = cur.right;
}
cur = stack.pop();
cur.val += pre;
pre = cur.val;
cur = cur.left;
}
return root;
};
```
----------------------- -----------------------
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)