mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
0235二叉搜索树的最近公共祖先Javascript版本
This commit is contained in:
@ -312,8 +312,46 @@ func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
|
|||||||
}else {return findLeft}
|
}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;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user