mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
update 0235.二叉搜索树的最近公共祖先: 替换 go 代码
This commit is contained in:
@ -303,14 +303,22 @@ class Solution:
|
||||
|
||||
递归法:
|
||||
```go
|
||||
//利用BSL的性质(前序遍历有序)
|
||||
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
|
||||
if root==nil{return nil}
|
||||
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)
|
||||
}else {return root}//当前节点的值在给定值的中间(或者等于),即为最深的祖先
|
||||
if root == nil {
|
||||
return nil
|
||||
}
|
||||
for {
|
||||
if root.Val > p.Val && root.Val > q.Val {
|
||||
root = root.Left
|
||||
}
|
||||
if root.Val < p.Val && root.Val < q.Val {
|
||||
root = root.Right
|
||||
}
|
||||
if (root.Val - p.Val) * (root.Val - q.Val) <= 0 {
|
||||
return root
|
||||
}
|
||||
}
|
||||
return root
|
||||
}
|
||||
```
|
||||
|
||||
@ -326,11 +334,11 @@ var lowestCommonAncestor = function(root, p, q) {
|
||||
if(root === null) {
|
||||
return root;
|
||||
}
|
||||
if(root.val>p.val&&root.val>q.val) {
|
||||
if(root.val > p.val && root.val > q.val) {
|
||||
// 向左子树查询
|
||||
return root.left = lowestCommonAncestor(root.left,p,q);
|
||||
}
|
||||
if(root.val<p.val&&root.val<q.val) {
|
||||
if(root.val < p.val && root.val < q.val) {
|
||||
// 向右子树查询
|
||||
return root.right = lowestCommonAncestor(root.right,p,q);
|
||||
}
|
||||
@ -343,9 +351,9 @@ var lowestCommonAncestor = function(root, p, q) {
|
||||
var lowestCommonAncestor = function(root, p, q) {
|
||||
// 使用迭代的方法
|
||||
while(root) {
|
||||
if(root.val>p.val&&root.val>q.val) {
|
||||
if(root.val > p.val && root.val > q.val) {
|
||||
root = root.left;
|
||||
}else if(root.val<p.val&&root.val<q.val) {
|
||||
}else if(root.val < p.val && root.val < q.val) {
|
||||
root = root.right;
|
||||
}else {
|
||||
return root;
|
||||
|
Reference in New Issue
Block a user