Poison

235. Lowest Common Ancestor of a Binary Search Tree

Recursion
1
2
3
4
5
6
7
8
9
10
11
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
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;
}
}
}
Recursion
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (p.val > q.val) {
return lowestCommonAncestor(root, q, p);
}

if (root.val < p.val) {
return lowestCommonAncestor(root.right, p, q);
} else if (root.val > q.val) {
return lowestCommonAncestor(root.left, p, q);
} else {
return root;
}
}
}
Iterate
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while (true) {
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;
}
}
}
}
Reference

235. Lowest Common Ancestor of a Binary Search Tree
剑指 Offer 68 - I. 二叉搜索树的最近公共祖先