Finding the Lowest Common Ancestor
Follow the two root paths and locate the deepest node they have in common.
Core Intuition & How It Works
The Lowest Common Ancestor (LCA) of two nodes p and q is the deepest node that has both p and q as descendants. A single postorder DFS returns whichever target it finds and identifies the split point where both subtrees report a match.
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(n) general tree, O(h) BST |
| Space Complexity | O(h) |
| Topic Chapter | Chapter 7: Trees |
| Difficulty Level | Intermediate |
Key Pattern to Recognize
If both left and right recursive calls return non-null, the current node is the LCA; otherwise propagate the non-null result upward.
Common Pitfalls & Edge Cases
Forgetting that a node can be an ancestor of itself, or not verifying both nodes exist when the problem allows missing targets.
Real-World & Technical Interview Applications
Git merge-base commits, network routing hierarchies, taxonomy queries, and distance between tree nodes.