File tree Expand file tree Collapse file tree 1 file changed +19
-12
lines changed Expand file tree Collapse file tree 1 file changed +19
-12
lines changed Original file line number Diff line number Diff line change 48
48
49
49
在有序树里,如果判断一个节点的左子树里有p,右子树里有q呢?
50
50
51
- 因为是有序树,所有 如果 中间节点是 q 和 p 的公共祖先,那么 中节点的数组 一定是在 [ p, q] 区间的。即 中节点 > p && 中节点 < q 或者 中节点 > q && 中节点 < p。
51
+ 因为是有序树,所以 如果 中间节点是 q 和 p 的公共祖先,那么 中节点的数组 一定是在 [ p, q] 区间的。即 中节点 > p && 中节点 < q 或者 中节点 > q && 中节点 < p。
52
52
53
53
那么只要从上到下去遍历,遇到 cur节点是数值在[ p, q] 区间中则一定可以说明该节点cur就是p 和 q的公共祖先。 那问题来了,** 一定是最近公共祖先吗** ?
54
54
@@ -328,28 +328,35 @@ class Solution:
328
328
```
329
329
### Go
330
330
331
- 递归法:
331
+ 递归法
332
332
``` go
333
333
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
336
340
}
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 {
339
349
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 {
342
351
root = root.Right
343
- }
344
- if (root.Val - p.Val ) * (root.Val - q.Val ) <= 0 {
352
+ } else {
345
353
return root
346
354
}
347
355
}
348
- return root
356
+ return nil
349
357
}
350
358
```
351
359
352
-
353
360
### JavaScript
354
361
355
362
递归法:
You can’t perform that action at this time.
0 commit comments