mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
Revert "0235二叉搜索树的最近公共祖先"
This reverts commit c0dbcc8a73eec6517b8b26e376a8c7060b8b858b.
This commit is contained in:
@ -312,46 +312,7 @@ 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