In a family tree, the closest shared ancestor of two cousins is their grandparent. In a rooted tree, the lowest common ancestor (LCA) of two nodes is the deepest node that has both of them below it. LCA queries appear in network routing, file systems, version control and many tree problems, such as finding the distance between two nodes. This lesson starts with the simple walking method and then builds binary lifting, which answers each query in O(log n).
In this lesson you will learn
- What the lowest common ancestor is
- The simple method: walk up until the nodes meet
- How the binary lifting table up[k][v] is built
- Answering LCA queries in O(log n)
- Finding the distance between two nodes
- The quick method for binary search trees
You should know binary trees, binary search trees and bit manipulation.
The Example Tree
- LCA(7, 9) = 2: node 7 is under 4, node 9 is under 5, and both 4 and 5 are children of 2.
- LCA(8, 9) = 5, their parent.
- LCA(7, 2) = 2: if one node is an ancestor of the other, it is the LCA.
The Simple Method
First move the deeper node up until both are at the same depth. Then move both up one step at a time until they meet.
#include <stdio.h>
/* Simple LCA for one query: walk both nodes up to the same depth, then together */
static int parent_of[] = {0, 0, 1, 1, 2, 2, 3, 4, 5, 5};
static int depth_of(int v) { int d = 0; while (parent_of[v]) { v = parent_of[v]; d++; } return d; }
static int lca_naive(int a, int b, int *steps) {
int da = depth_of(a), db = depth_of(b);
*steps = 0;
while (da > db) { a = parent_of[a]; da--; (*steps)++; }
while (db > da) { b = parent_of[b]; db--; (*steps)++; }
while (a != b) { a = parent_of[a]; b = parent_of[b]; (*steps)++; }
return a;
}
/* LCA in a binary search tree: no parent pointers needed */
static int lca_bst(int root_val, const int *left, const int *right, int x, int y) {
int v = root_val;
while (1) {
if (x < v && y < v) v = left[v];
else if (x > v && y > v) v = right[v];
else return v; /* x and y split here (or one of them is v) */
}
}
int main(void) {
int steps;
int c = lca_naive(7, 9, &steps);
printf("Naive LCA(7, 9) = %d after %d steps\n", c, steps);
/* BST: 20
/ \
10 30
/ \ \
5 15 40 (left/right indexed by value) */
int left[41] = {0}, right[41] = {0};
left[20] = 10; right[20] = 30; left[10] = 5; right[10] = 15; right[30] = 40;
printf("BST LCA(5, 15) = %d\n", lca_bst(20, left, right, 5, 15));
printf("BST LCA(5, 40) = %d\n", lca_bst(20, left, right, 5, 40));
printf("BST LCA(10, 15) = %d\n", lca_bst(20, left, right, 10, 15));
return 0;
}
Output
Naive LCA(7, 9) = 2 after 2 steps
BST LCA(5, 15) = 10
BST LCA(5, 40) = 20
BST LCA(10, 15) = 10
- This takes O(height) steps per query. In a long, thin tree that can be O(n), which is too slow for many queries.
- In a binary search tree, we can start at the root instead. If both values are smaller, go left; if both are bigger, go right. The first node where they split up is the LCA.
Binary Lifting
Instead of moving one step at a time, we jump in powers of two. We store:
up[0][v] = parent of v
up[k][v] = the ancestor 2^k levels above v = up[k−1][ up[k−1][v] ]
Jumping 2k levels is two jumps of 2k−1. Any distance can be made from these jumps, just as any number can be written in binary.
#include <stdio.h>
#define N 10
#define LOG 4
/* Tree (root 1): 1
/ \
2 3
/ \ \
4 5 6
/ / \
7 8 9 */
static int parent_of[N] = {0, 0, 1, 1, 2, 2, 3, 4, 5, 5};
static int up[LOG][N], depth[N];
static int lca(int a, int b) {
if (depth[a] < depth[b]) { int t = a; a = b; b = t; }
int diff = depth[a] - depth[b];
for (int k = 0; k < LOG; k++) /* lift a to b's depth using binary jumps */
if (diff & (1 << k)) a = up[k][a];
if (a == b) return a;
for (int k = LOG - 1; k >= 0; k--) /* lift both while their ancestors differ */
if (up[k][a] != up[k][b]) { a = up[k][a]; b = up[k][b]; }
return up[0][a];
}
int main(void) {
/* nodes are numbered so a parent always comes before its children */
for (int v = 1; v < N; v++) {
up[0][v] = parent_of[v] ? parent_of[v] : v; /* root points to itself */
depth[v] = parent_of[v] ? depth[parent_of[v]] + 1 : 0;
}
for (int k = 1; k < LOG; k++)
for (int v = 1; v < N; v++) up[k][v] = up[k - 1][up[k - 1][v]];
printf("node : ");
for (int v = 1; v < N; v++) printf("%2d", v);
printf("\ndepth: ");
for (int v = 1; v < N; v++) printf("%2d", depth[v]);
printf("\nup[1]: ");
for (int v = 1; v < N; v++) printf("%2d", up[1][v]);
printf(" (grandparent)\n\n");
int qs[][2] = {{7, 9}, {8, 9}, {4, 6}, {7, 2}};
for (int i = 0; i < 4; i++) {
int a = qs[i][0], b = qs[i][1], c = lca(a, b);
printf("LCA(%d, %d) = %d, distance = %d\n", a, b, c, depth[a] + depth[b] - 2 * depth[c]);
}
return 0;
}
Output
node : 1 2 3 4 5 6 7 8 9
depth: 0 1 1 2 2 2 3 3 3
up[1]: 1 1 1 1 1 1 2 2 2 (grandparent)
LCA(7, 9) = 2, distance = 4
LCA(8, 9) = 5, distance = 2
LCA(4, 6) = 1, distance = 4
LCA(7, 2) = 2, distance = 2
- The root’s parent is set to itself, so jumping past the root stays at the root.
- Step 1: lift the deeper node by the depth difference. Each set bit of the difference is one jump. A difference of 5 (binary 101) is a jump of 4 and a jump of 1.
- Step 2: if the nodes are now equal, that node is the LCA. Otherwise, try jumps from the largest down. Jump both nodes only if they would land on different ancestors. At the end they are just below the LCA, so the answer is their parent.
- Building the table takes O(n log n). Each query takes O(log n).
- The distance between two nodes is depth[a] + depth[b] − 2 × depth[LCA]. For 7 and 9 that is 3 + 3 − 2 = 4 edges: 7 → 4 → 2 → 5 → 9.
Methods Compared
| Method | Preparation | Per query |
|---|---|---|
| Walk up step by step | O(n) for depths | O(height) |
| Binary lifting | O(n log n) | O(log n) |
| Euler tour + sparse table | O(n log n) | O(1) |
| BST walk from root | None | O(height) |
Binary lifting is also useful on its own: it finds the k-th ancestor of any node in O(log k).
Common Mistakes
- Skipping the depth-equalising step, so the two nodes never meet.
- Jumping when the ancestors are equal in step 2, which overshoots the LCA.
- Building up[k] before up[k−1] is complete.
- Using too few levels: LOG must satisfy 2LOG > the tree’s height.
Practice Exercises
Exercise 1. In the example tree, find LCA(9, 6) and the distance between 9 and 6.
Show answer
LCA is 1 (the root). Distance = 3 + 2 − 2 × 0 = 5 edges: 9 → 5 → 2 → 1 → 3 → 6.
Exercise 2. Using up[k][v], how do you find the 3rd ancestor of node 7?
Show answer
3 = 2 + 1, so jump up[1] then up[0]: 7 → 2 (grandparent) → 1. The 3rd ancestor of 7 is 1.
Frequently Asked Questions
How do I build the table for a tree given as edges?
Run a BFS or DFS from the root. When you first reach a node, set its parent and depth. Then fill the up table level by level.
Where is LCA used in real software?
Git uses a similar idea to find the merge base of two branches, and network tools use it to find where two routes in a tree-shaped network meet.
Summary
- The LCA is the deepest node that is an ancestor of both nodes.
- up[k][v] stores the 2k-th ancestor and is built from up[k−1].
- Lift to equal depth, then lift both while their ancestors differ; the parent is the LCA.
- Distance = depth[a] + depth[b] − 2 × depth[LCA].
