mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +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
|
||||
}
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user