Introduction
LCA in BST means:
- finding nearest common parent
- of two nodes
- using BST properties
BST Property:
Left subtree values < Root value < Right subtree valuesGoal:
- efficiently locate
lowest common ancestor
Example:
6/ \
2 8
/ \ / \
0 4 7 9
/ \
3 5
Nodes:
2 and 8
LCA:
6
Explanation:
6 is the first node that splits both nodes into different subtrees. This problem is one of the most important applications of:
DFS TraversalConstraints
1 <= Number of Nodes <= 10^5Approach : BST Recursive DFS Solution
Explanations:
Explanation:
The idea is:
- use BST ordering property
- traverse only required subtree
Steps:
- Visit current node.
- Compare target values.
- Move left if both smaller.
- Move right if both larger.
- Current node becomes LCA otherwise.
Conditions:
p < root and q < root → move leftp > root and q > root → move rightOtherwise:
Current node is LCA This approach:
- uses DFS recursion
- optimizes traversal using BST rules
Dry Run
Visit:6
Nodes:
2 and 8
2 is smaller than 6
8 is greater than 6
Nodes split here.
LCA:
6
Practice :