TreesAnimated
Lowest Common Ancestor (LCA)
The deepest node that has both targets in its subtree.
Time
O(h)
Extra space
O(1)
Use it for
Distance between nodes, family trees.
How it works
- In a binary search tree the lowest common ancestor is the first node where the two keys "split" (one is smaller, the other larger).
- Start at the root. If both keys are smaller, go left; if both are larger, go right.
- The moment they split (or one equals the current node), the current node is the LCA.
- O(height).
Watch it run
Loading animation…