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: "The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself)."
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Tree:
6
/ \
2 8
/ \ / \
0 4 7 9
/ \
3 5
Explanation: LCA of 2 and 8 is 6 (root)
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: LCA of 2 and 4 is 2 (node can be ancestor of itself)
Input: root = [2,1], p = 2, q = 1
Output: 2
The BST property is key: left < root < right
For nodes p and q, the LCA is the split point where:
Key insight: Use BST property to navigate without searching entire tree!
If both p and q are:
This is a BST Property Exploitation problem with:
while current:
if p.val < current.val and q.val < current.val:
current = current.left # Both in left subtree
elif p.val > current.val and q.val > current.val:
current = current.right # Both in right subtree
else:
return current # Found split point (LCA)
Why this works:
def lowestCommonAncestor(root, p, q):
if p.val < root.val and q.val < root.val:
return lowestCommonAncestor(root.left, p, q)
if p.val > root.val and q.val > root.val:
return lowestCommonAncestor(root.right, p, q)
return root
Time: O(h) where h = height of tree
Space:
1class TreeNode {
2 int val;
3 TreeNode left;
4 TreeNode right;
5 TreeNode(int x) { val = x; }
6}
7
8class Solution {
9 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
10 TreeNode current = root;
11
12 while (current != null) {
13 // Both p and q are in left subtree
14 if (p.val < current.val && q.val < current.val) {
15 current = current.left;
16 }
17 // Both p and q are in right subtree
18 else if (p.val > current.val && q.val > current.val) {
19 current = current.right;
20 }
21 // Found the split point (LCA)
22 else {
23 return current;
24 }
25 }
26
27 return null; // Should never reach here if p and q are in tree
28 }
29}
30