update 0235.二叉搜索树的最近公共祖先: 替换 go 代码

This commit is contained in:
Yuhao Ju
2022-12-04 23:10:10 +08:00
committed by GitHub
parent c5fa95ebff
commit 1287679e8e

View File

@ -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
}
```