提供Javascript版本的《二叉搜索数的最近公共祖先》

This commit is contained in:
kok-s0s
2021-06-23 21:49:11 +08:00
parent e719e4f647
commit bf7597facf

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;
};
```
-----------------------