235 Lowest Common Ancestor of a Binary Search Tree

# 1. Question

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
1
_______6______
2
/ \
3
___2__ ___8__
4
/ \ / \
5
0 _4 7 9
6
/ \
7
3 5
Copied!
For example, the lowest common ancestor (LCA) of nodes`2`and`8`is`6`. Another example is LCA of nodes`2`and`4`is`2`, since a node can be a descendant of itself according to the LCA definition.

# 2. Implementation

(1) Recursion
1
class Solution {
2
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
3
if (root.val < Math.min(p.val, q.val)) {
4
return lowestCommonAncestor(root.right, p, q);
5
}
6
else if (root.val > Math.max(p.val, q.val)) {
7
return lowestCommonAncestor(root.left, p, q);
8
}
9
else {
10
return root;
11
}
12
}
13
}
Copied!
(2) Iteration
1
class Solution {
2
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
3
TreeNode curNode = root;
4
while (curNode != null) {
5
if (curNode.val < p.val && curNode.val < q.val) {
6
curNode = curNode.right;
7
}
8
else if (curNode.val > p.val && curNode.val > q.val) {
9
curNode = curNode.left;
10
}
11
else {
12
break;
13
}
14
}
15
return curNode;
16
}
17
}
Copied!

# 3. Time & Space Complexity

Recursion: 时间复杂度: O(h), 空间复杂度: O(h)
Iteration: 时间复杂度:O(h) , 空间复杂度：O(1)