Lowest Common Ancestor
Tree edges:
LCA · climb up
–
Pseudocode
1depth[], parent[] ← a DFS from the root2while depth[u] > depth[v]: u ← parent[u]3while depth[v] > depth[u]: v ← parent[v]4while u ≠ v: u ← parent[u]; v ← parent[v]5return u // the first common ancestor
Pointer moves
0
u / vthe two pointerspathwhere they climbed (pale yellow)the lowest common ancestor
What is the Lowest Common Ancestor?
In a rooted tree, the lowest common ancestor (LCA) of two nodes u and v is the deepest node that has both of them below it. In a family tree it is the closest shared ancestor; in a file system, the deepest folder containing both files.
The simple way is to climb: bring the deeper node up to the other's depth, then move both up one step at a time until they meet. That costs up to the height of the tree per question. Binary lifting precomputes every node's 1st, 2nd, 4th, 8th… ancestor, so the same climb can be done in big power-of-two jumps: O(log n) per question.
Bring both nodes to the same depth, then climb together until they meet.
Using the Visualizer
- • Pick u and v, and choose Climb up or Binary lifting.
- • Pale yellow nodes are where the pointers have been; the green node is the answer.
- • With binary lifting, the table on the right fills one row (power of two) at a time; a green cell is the jump being used.
- • Type your own tree as edges like 0-1, 0-2, 1-3 (rooted at 0) and press Apply.
How It Works
1. Depths
One DFS from the root gives every node's parent and depth.
2. Level them
Move the deeper node up until both have the same depth.
3. Climb together
Move both up until they are the same node: that is the LCA.
Binary lifting
Same idea with jumps of 2ᵏ: use the binary digits of the depth difference, then jump both while their 2ᵏ-ancestors differ.
Implementation
Properties & Complexity
Time Complexity
- • Climb: O(h) per query, h = tree height (up to n)
- • Binary lifting: O(n log n) to build, O(log n) per query
- • Euler tour + RMQ: O(1) per query after O(n log n)
Space & Properties
- • Climb: O(n) for parent and depth
- • Binary lifting: O(n log n) for the table
Where It Is Used
- • Distance between two nodes: depth[u] + depth[v] − 2·depth[LCA]
- • Version control: git's merge base is a common ancestor of two commits
- • Biology: closest common ancestor in an evolutionary tree
- • Network routing in tree-shaped networks
Limitations
- • Rooted trees: the answer depends on the root
- • Static: the table must be rebuilt if the tree changes