Lowest Common Ancestor of a Binary Search Tree - Problem
Given a Binary Search Tree (BST), find the lowest common ancestor (LCA) node of two given nodes p and q in the BST.
The lowest common ancestor is defined as the lowest node in the tree that has both p and q as descendants. Note that a node can be a descendant of itself.
๐ณ Key Insight: In a BST, all nodes in the left subtree are smaller than the root, and all nodes in the right subtree are larger. This property makes finding the LCA much more efficient than in a regular binary tree!
Example: If we have nodes with values 2 and 8 in a BST, and the root is 6, then 6 is their LCA because 2 < 6 < 8, meaning they diverge at node 6.
Input & Output
example_1.py โ Basic LCA
$
Input:
root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
โบ
Output:
6
๐ก Note:
The LCA of nodes 2 and 8 is 6, since 2 < 6 < 8, making 6 the split point where their paths diverge.
example_2.py โ LCA with ancestor relationship
$
Input:
root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
โบ
Output:
2
๐ก Note:
The LCA of nodes 2 and 4 is 2, since node 2 is an ancestor of node 4 (and a node can be an ancestor of itself).
example_3.py โ Simple tree
$
Input:
root = [2,1,3], p = 1, q = 3
โบ
Output:
2
๐ก Note:
The LCA of nodes 1 and 3 is 2, since 1 < 2 < 3, making 2 the root where paths to both nodes split.
Constraints
- The number of nodes in the tree is in the range [2, 105]
- -109 โค Node.val โค 109
- All Node.val are unique
- p โ q
- Both p and q will exist in the BST
Visualization
Tap to expand
Understanding the Visualization
1
Start at Peak
Begin at the root of the BST
2
Check Direction
Compare both targets with current elevation
3
Navigate Smart
Go left if both lower, right if both higher
4
Find Split
When targets are on different sides, you found the junction
Key Takeaway
๐ฏ Key Insight: In a BST, the LCA is the first node where the paths to p and q diverge - when one target is โค current node and the other is โฅ current node.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code