Merge pull request #436 from kok-s0s/master

提供二叉树部分的JavaScript代码
This commit is contained in:
程序员Carl
2021-06-24 15:21:58 +08:00
committed by GitHub
2 changed files with 88 additions and 0 deletions

View File

@ -314,7 +314,62 @@ func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
``` ```
JavaScript版本
> 递归
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {TreeNode} p
* @param {TreeNode} q
* @return {TreeNode}
*/
var lowestCommonAncestor = function(root, p, q) {
if(root.val > p.val && root.val > q.val)
return lowestCommonAncestor(root.left, p , q);
else if(root.val < p.val && root.val < q.val)
return lowestCommonAncestor(root.right, p , q);
return root;
};
```
> 迭代
```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {TreeNode} p
* @param {TreeNode} q
* @return {TreeNode}
*/
var lowestCommonAncestor = function(root, p, q) {
while(1) {
if(root.val > p.val && root.val > q.val)
root = root.left;
else if(root.val < p.val && root.val < q.val)
root = root.right;
else
break;
}
return root;
};
```
----------------------- -----------------------

View File

@ -286,6 +286,39 @@ func insertIntoBST(root *TreeNode, val 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
* @param {number} val
* @return {TreeNode}
*/
var insertIntoBST = function (root, val) {
const setInOrder = (root, val) => {
if (root === null) {
let node = new TreeNode(val);
return node;
}
if (root.val > val)
root.left = setInOrder(root.left, val);
else if (root.val < val)
root.right = setInOrder(root.right, val);
return root;
}
return setInOrder(root, val);
};
```