-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNo68NearestCommonAncestorOfBinarySearchTree.java
More file actions
61 lines (55 loc) · 1.46 KB
/
No68NearestCommonAncestorOfBinarySearchTree.java
File metadata and controls
61 lines (55 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.wzx.sword;
import com.wzx.entity.TreeNode;
/**
* @see <a href="https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-zui-jin-gong-gong-zu-xian-lcof/">https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-zui-jin-gong-gong-zu-xian-lcof/</a>
* @author wzx
*/
public class No68NearestCommonAncestorOfBinarySearchTree {
/**
* 递归
* <p>
* time: O(h) h树高
* space: O(h)
*/
public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) return null;
if (root.val > p.val && root.val > q.val) {
// 都在左子树
return lowestCommonAncestor1(root.left, p, q);
} else if (root.val < p.val && root.val < q.val) {
// 都在右子树
return lowestCommonAncestor1(root.right, p, q);
} else {
// 不同侧
return root;
}
}
/**
* 迭代
* <p>
* time: O(h) h树高
* space: O(1)
*/
public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
// 迭代前约束p,q大小关系
if (p.val > q.val) {
TreeNode tmp = p;
p = q;
q = tmp;
}
while (root != null) {
// 迭代前约束了大小, 所以可以减少判断一个条件
if (root.val > q.val) {
// 都在左子树
root = root.left;
} else if (root.val < p.val) {
// 都在右子树
root = root.right;
} else {
// 不同侧
return root;
}
}
return null;
}
}