π Why This Pattern Matters?
The Lowest Common Ancestor (LCA) is a fundamental tree problem where you need to find the lowest (deepest) node in the tree that has both given nodes as descendants.
This is one of the most reusable patterns in interviews, often appearing in many variations (in Binary Tree, BST, K nodes, distance between nodes, etc.).
Once you master LCA, a whole class of problems feels simple.
π Core Idea / Template
- Binary Tree (General):
- Recurse into left and right subtrees.
- If both sides return non-null, current node = LCA.
- If one side is null, return the other side.
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) return root;
return left != null ? left : right;
}
}
- Binary Search Tree (BST):
- Use property:
p < root < q
. - If both
p
andq
are smaller β go left. - If both greater β go right.
- Else root is LCA.
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while (root != null) {
if (p.val < root.val && q.val < root.val) {
root = root.left;
} else if (p.val > root.val && q.val > root.val) {
root = root.right;
} else {
return root;
}
}
return null;
}
}
β Classic Problems
1. LCA in Binary Tree (LeetCode 236)
- Use general recursive template (above).
- Trick: Works even if tree is not BST.
2. LCA in BST (LeetCode 235)
- Uses BST property (O(log N) instead of O(N)).
- Best when interviewer specifies BST.
3. Distance Between Two Nodes
- Formula:
dist(u, v) = dist(root, u) + dist(root, v) - 2 * dist(root, lca(u, v))
- Steps:
- Find
lca(u, v)
. - Use DFS to compute distance from root to any node.
- Apply formula.
4. Nodes on Path Between Two Nodes
- Get
LCA
. -
Collect path:
- From
u β LCA
. - From
v β LCA
.
- From
Merge them (avoiding duplicate LCA).
π Advanced Variations
- LCA of K Nodes (not just 2):
- Generalize by recursive reduction: LCA of (a, b, c, d) = LCA(a, LCA(b, LCA(c, d))).
- LCA in Tree with Parent Pointers:
- Store visited ancestors of one node in a set.
- Traverse other nodeβs parents until first match.
- LCA in DAG (Directed Acyclic Graph):
- Much harder (not covered in interviews unless senior).
π― Quick Pattern Checklist
- β If general Binary Tree β use recursive divide & conquer.
- β If BST β use value-based traversal.
- β If asked about distance/path β use LCA + DFS distance.
- β If multiple nodes β reduce step by step using pairwise LCA.
π₯ Key Takeaway:
Once you have the LCA tool in your arsenal, you can derive multiple tree distance/path problems in 2-3 lines of logic. This is a must-know pattern for FAANG interviews.
Top comments (0)