0235二叉搜索树的最近公共祖先Javascript版本

This commit is contained in:
xeniaxie(xl)
2021-06-27 10:45:48 +08:00
parent 1e6265d679
commit 53ce92f95f

View File

@ -312,8 +312,46 @@ func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
}else {return findLeft}
}
```
JavaScript版本
1. 使用递归的方法
```javascript
var lowestCommonAncestor = function(root, p, q) {
// 使用递归的方法
// 1. 使用给定的递归函数lowestCommonAncestor
// 2. 确定递归终止条件
if(root === null) {
return root;
}
if(root.val>p.val&&root.val>q.val) {
// 向左子树查询
let left = lowestCommonAncestor(root.left,p,q);
return left !== null&&left;
}
if(root.val<p.val&&root.val<q.val) {
// 向右子树查询
let right = lowestCommonAncestor(root.right,p,q);
return right !== null&&right;
}
return root;
};
```
2. 使用迭代的方法
```javascript
var lowestCommonAncestor = function(root, p, q) {
// 使用迭代的方法
while(root) {
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 {
return root;
}
}
return null;
};
```