Merge pull request #463 from kok-s0s/master

提供二叉树部分的JavaScript代码
This commit is contained in:
程序员Carl
2021-07-05 10:34:24 +08:00
committed by GitHub
2 changed files with 93 additions and 0 deletions

View File

@ -350,6 +350,36 @@ func sortedArrayToBST(nums []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 {number[]} nums
* @return {TreeNode}
*/
var sortedArrayToBST = function (nums) {
const buildTree = (Arr, left, right) => {
if (left > right)
return null;
let mid = Math.floor(left + (right - left) / 2);
let root = new TreeNode(Arr[mid]);
root.left = buildTree(Arr, left, mid - 1);
root.right = buildTree(Arr, mid + 1, right);
return root;
}
return buildTree(nums, 0, nums.length - 1);
};
```

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)