mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Merge pull request #2382 from markwang1992/master
更新0235二叉搜索树的最近公共祖先Go版本
This commit is contained in:
@ -48,7 +48,7 @@
|
|||||||
|
|
||||||
在有序树里,如果判断一个节点的左子树里有p,右子树里有q呢?
|
在有序树里,如果判断一个节点的左子树里有p,右子树里有q呢?
|
||||||
|
|
||||||
因为是有序树,所有 如果 中间节点是 q 和 p 的公共祖先,那么 中节点的数组 一定是在 [p, q]区间的。即 中节点 > p && 中节点 < q 或者 中节点 > q && 中节点 < p。
|
因为是有序树,所以 如果 中间节点是 q 和 p 的公共祖先,那么 中节点的数组 一定是在 [p, q]区间的。即 中节点 > p && 中节点 < q 或者 中节点 > q && 中节点 < p。
|
||||||
|
|
||||||
那么只要从上到下去遍历,遇到 cur节点是数值在[p, q]区间中则一定可以说明该节点cur就是p 和 q的公共祖先。 那问题来了,**一定是最近公共祖先吗**?
|
那么只要从上到下去遍历,遇到 cur节点是数值在[p, q]区间中则一定可以说明该节点cur就是p 和 q的公共祖先。 那问题来了,**一定是最近公共祖先吗**?
|
||||||
|
|
||||||
@ -328,27 +328,34 @@ class Solution:
|
|||||||
```
|
```
|
||||||
### Go
|
### Go
|
||||||
|
|
||||||
递归法:
|
递归法
|
||||||
```go
|
```go
|
||||||
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
|
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
|
||||||
if root == nil {
|
if root.Val > p.Val && root.Val > q.Val {
|
||||||
return nil
|
return lowestCommonAncestor(root.Left, p, q)
|
||||||
}
|
} else if root.Val < p.Val && root.Val < q.Val {
|
||||||
for {
|
return lowestCommonAncestor(root.Right, p, q)
|
||||||
if root.Val > p.Val && root.Val > q.Val {
|
} else {
|
||||||
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
|
return root
|
||||||
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
迭代法
|
||||||
|
```go
|
||||||
|
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
|
||||||
|
for root != nil {
|
||||||
|
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 nil
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### JavaScript
|
### JavaScript
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user