Skip to content

Commit 4223cad

Browse files
Merge pull request #2382 from markwang1992/master
更新0235二叉搜索树的最近公共祖先Go版本
2 parents 3baabbc + 95e8b27 commit 4223cad

File tree

1 file changed

+19
-12
lines changed

1 file changed

+19
-12
lines changed

problems/0235.二叉搜索树的最近公共祖先.md

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848

4949
在有序树里,如果判断一个节点的左子树里有p,右子树里有q呢?
5050

51-
因为是有序树,所有 如果 中间节点是 q 和 p 的公共祖先,那么 中节点的数组 一定是在 [p, q]区间的。即 中节点 > p && 中节点 < q 或者 中节点 > q && 中节点 < p。
51+
因为是有序树,所以 如果 中间节点是 q 和 p 的公共祖先,那么 中节点的数组 一定是在 [p, q]区间的。即 中节点 > p && 中节点 < q 或者 中节点 > q && 中节点 < p。
5252

5353
那么只要从上到下去遍历,遇到 cur节点是数值在[p, q]区间中则一定可以说明该节点cur就是p 和 q的公共祖先。 那问题来了,**一定是最近公共祖先吗**
5454

@@ -328,28 +328,35 @@ class Solution:
328328
```
329329
### Go
330330

331-
递归法
331+
递归法
332332
```go
333333
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
334-
if root == nil {
335-
return nil
334+
if root.Val > p.Val && root.Val > q.Val {
335+
return lowestCommonAncestor(root.Left, p, q)
336+
} else if root.Val < p.Val && root.Val < q.Val {
337+
return lowestCommonAncestor(root.Right, p, q)
338+
} else {
339+
return root
336340
}
337-
for {
338-
if root.Val > p.Val && root.Val > q.Val {
341+
}
342+
```
343+
344+
迭代法
345+
```go
346+
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
347+
for root != nil {
348+
if root.Val > p.Val && root.Val > q.Val {
339349
root = root.Left
340-
}
341-
if root.Val < p.Val && root.Val < q.Val {
350+
} else if root.Val < p.Val && root.Val < q.Val {
342351
root = root.Right
343-
}
344-
if (root.Val - p.Val) * (root.Val - q.Val) <= 0 {
352+
} else {
345353
return root
346354
}
347355
}
348-
return root
356+
return nil
349357
}
350358
```
351359

352-
353360
### JavaScript
354361

355362
递归法:

0 commit comments

Comments
 (0)