Heavy-Light & Centroid Decomposition
Breaking trees into paths and parts for fast path queries.
A path in a tree of a million nodes can be a million edges long, yet any path can be cut into at most 39 pieces that are contiguous ranges of one array, so a segment tree answers path sums and path maximums with at most 39 range queries. Heavy-light decomposition does the cutting. Centroid decomposition cuts the tree at balance points instead, so that every path is handled at a single centroid and every vertex lies in only of the pieces. Between them, the two techniques solve most path problems on static trees, and they lead to the dynamic trees behind fast maximum-flow algorithms.
What you’ll learn
- Define heavy and light edges, and prove that every root-to-node path crosses fewer than light edges.
- Lay heavy paths out contiguously, and answer path queries with at most segment-tree ranges, in total, and subtree queries with one range.
- Prove that every tree has one centroid or two adjacent ones, and build the centroid decomposition with at most levels in time.
- Count paths with a property by divide and conquer over centroids, and place link-cut trees, Euler-tour trees and top trees against the cell-probe lower bound.
Heavy and light edges
A light edge more than doubles the size. If is light, has a heavy child with :
Climb to the root. Subtree sizes never decrease on the way up, and each light edge more than doubles them. After light edges:
Heavy paths. Between consecutive light edges the climb stays on one heavy path, so it meets of them. The bound is tight: in a perfect binary tree of height , always stepping to the light child crosses light edges.
Sleator and Tarjan (1983) introduced the partition for their dynamic trees, calling the edge from to its parent heavy when . Under that rule a node has at most one heavy child, possibly none, and a light edge at least doubles the size, so at most light edges lie on any root path; Harel and Tarjan (1984) built their constant-time LCA structure on such a decomposition. The largest-child rule used in contests gives every non-leaf exactly one heavy child.
Now number the nodes by a preorder that always visits the heavy child first. The heavy child then gets the position right after its parent, so every heavy path occupies consecutive positions; and as in any preorder, the subtree of occupies exactly .
Path queries in O(log² n)
Store each node's value at its position and build a segment tree over the array. To aggregate a path –: while and lie on different heavy paths, take the one whose head is deeper, query the range from its head down to it, and jump to the head's parent. Once both are on one heavy path, the shallower of the two is the LCA, and one last range finishes the path.
#include <utility>
#include <vector>
using namespace std;
struct HLD {
vector<int> par, dep, heavy, head, pos;
HLD(const vector<vector<int>>& ch) { // children lists, root 0
int n = ch.size(), cur = 0;
par.assign(n, -1); dep.assign(n, 0); heavy.assign(n, -1); head.assign(n, 0); pos.assign(n, 0);
vector<int> order = {0}, sz(n, 1);
for (int i = 0; i < (int)order.size(); ++i) // BFS: parents before children
for (int c : ch[order[i]]) { par[c] = order[i]; dep[c] = dep[order[i]] + 1; order.push_back(c); }
for (int i = n - 1; i > 0; --i) sz[par[order[i]]] += sz[order[i]];
for (int v = 0; v < n; ++v)
for (int c : ch[v]) if (heavy[v] < 0 || sz[c] > sz[heavy[v]]) heavy[v] = c;
vector<int> st = {0}; // preorder, heavy child first
while (!st.empty()) {
int v = st.back(); st.pop_back();
head[v] = (v != 0 && heavy[par[v]] == v) ? head[par[v]] : v;
pos[v] = cur++;
for (int c : ch[v]) if (c != heavy[v]) st.push_back(c);
if (heavy[v] >= 0) st.push_back(heavy[v]); // popped next: heavy paths stay contiguous
}
}
template <class F> void path(int u, int v, F f) { // f(l, r) on O(log n) ranges covering u..v
while (head[u] != head[v]) {
if (dep[head[u]] < dep[head[v]]) swap(u, v);
f(pos[head[u]], pos[u]); // u's whole segment lies below the LCA
u = par[head[u]];
}
if (dep[u] > dep[v]) swap(u, v);
f(pos[u], pos[v]); // same heavy path; u is the LCA
}
};No recursion, so deep trees are safe. path hands each range to a callback, for a sum, a maximum or a lazy range update on the segment tree. For values on edges, store each edge at its lower endpoint and use in the last call, which skips the LCA. Compiled as C++17 and checked against brute force on 150,000 path queries over random trees.
A ═ B ═ D ═ H ═ N heavy path, positions 0–4
│ │ └── I positions 5 (I hangs from D)
│ └── E ═ J positions 6–7 (E hangs from B)
└── C ═ F ═ K ═ L positions 8–11 (C hangs from A)
└── G ═ M positions 12–13 (G hangs from C)
position 0 1 2 3 4 5 6 7 8 9 10 11 12 13
node A B D H N I E J C F K L G M
value 5 2 4 8 5 2 1 9 7 3 1 4 6 3A 14-node tree; ═ marks heavy edges. Subtree sizes: 14, 7, 6, 4, 3, and so on, so , , , and are heavy children.
In the same tree, into how many ranges does the procedure split the path from to ?
- 2
- 3
- 4
- 7
Show the answer
C. 4
is a heavy path by itself (position 5); then – (12–13); then alone (8), because 's heavy path continues down through , , , which are not on this path; finally – (0–2). Four ranges cover the seven nodes , with sum .
Centroids
Walk downhill. Start at any vertex . If some component of has more than vertices, step to 's neighbor in . The component of that contains is everything outside :
So the walk never steps back, visits each vertex at most once, and stops at a vertex all of whose components have at most vertices: a centroid. With subtree sizes computed once from any root, testing a vertex costs , so in all.
At most two, and adjacent. Let be centroids, the component of containing , and the component of containing . Every vertex lies in or in , and both have at most vertices:
A vertex strictly between and would lie in both and , so there is none: and are adjacent, and is even. Three centroids would be pairwise adjacent, a triangle, which a tree cannot contain.
How many centroids does a path of 8 vertices have?
- 1, the vertex in the exact middle
- 2, the two middle vertices, which are adjacent
- 8, since all vertices of a path look alike
- None, because 8 is even
Show the answer
B. 2, the two middle vertices, which are adjacent
Removing the 4th vertex leaves pieces of 3 and 4 vertices, and removing the 5th leaves 4 and 3; both are at most . Removing the 3rd leaves a piece of 5. So the 4th and 5th vertices are the two centroids, adjacent as the theorem promises.
Centroid decomposition: divide and conquer over all paths
Remove a centroid , then recurse on each component of . The centroids chosen form the centroid decomposition, a rooted tree of its own with at the top and the components' centroids as its children.
Levels. Each cut at a centroid at least halves component sizes, so a component at level has at most vertices, and a nonempty one has at least one:
Time. The components of one level are disjoint, and their centroids are found in time linear in their sizes, so each level costs :
Paths. Take a path . As long as none of its vertices has been removed, stays connected, inside one component. The first vertex of to be removed is therefore the centroid of that component:
So each of the pairs of vertices is handled at exactly one centroid. To count the pairs at distance at most , list at each centroid the distances from to all vertices of its component, count the pairs whose two distances sum to at most , and subtract the pairs that lie in one piece of the component minus : their path avoids , so the sum overstates their distance, and they are counted deeper.
COUNT(C): # pairs in component C at distance ≤ K
c ← CENTROID(C) # O(|C|), from subtree sizes
all ← [0] # c itself, at distance 0
total ← 0
for each component P of C − c:
dist ← distances from c to the vertices of P # one search, O(|P|)
total ← total − PAIRS(dist) # same piece: the path avoids c
all ← all + dist
total ← total + PAIRS(all) # pairs with d(x) + d(y) ≤ K
return total + Σ COUNT(P) over the components P of C − c
PAIRS(L): sort L, then count pairs i < j with L[i] + L[j] ≤ K by two pointersEach level sorts distances: in all. For distance exactly , counting arrays replace the sorting and give . A Python version was checked against breadth-first search from every vertex on 600 random trees; on paths the recursion uses exactly levels, so the bound is tight.
When the tree changes
Both decompositions assume a fixed tree. Sleator and Tarjan's link-cut trees (1983) maintain a forest under link (join two trees by an edge) and cut (delete an edge). They split each tree into preferred paths, chosen by recent accesses rather than by size, and keep each path in a balanced search tree ordered by depth. Accessing a node rebuilds the preferred paths along its root path; the heavy-light argument, made amortized, shows that only paths change per access. With splay trees (Sleator & Tarjan, 1985), every operation (link, cut, find the root, a path aggregate, an LCA) costs amortized. Their headline application was maximum flow in time.
Euler-tour trees (Henzinger & King, 1999; Tarjan, 1997) keep each tree's Euler tour in a balanced search tree. A link or a cut becomes a constant number of splits and concatenations of tours, so connectivity and subtree aggregates cost , but path aggregates are out of reach. Top trees (Alstrup, Holm, de Lichtenberg & Thorup, 2005) cluster the tree hierarchically and maintain both path and subtree information in per operation.
| Structure | Tree | Path aggregate | Subtree aggregate |
|---|---|---|---|
| Heavy-light + segment tree | fixed shape, changing values | ||
| Centroid decomposition | fixed | counting over all paths; nearest marked vertex in | not its purpose |
| Link-cut tree | link and cut, | only with an extension | |
| Euler-tour tree | link and cut, | not supported | |
| Top tree | link and cut, |
Key takeaways
- A heavy edge leads to a child with the largest subtree; every root path crosses fewer than light edges, because each one more than doubles the subtree size.
- A preorder that visits heavy children first makes every heavy path and every subtree a contiguous range: path queries take at most ranges, with a segment tree, and subtree queries one range.
- Every tree has one centroid or two adjacent ones. Removing centroids recursively gives at most levels in time, and every path is handled at the first of its vertices to be removed.
- Changing forests use link-cut trees (paths), Euler-tour trees (subtrees) or top trees (both) at per operation, which the Pătraşcu–Demaine cell-probe bound shows is optimal.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A rooted tree has 1,000 nodes. At most how many light edges can a path from the root to a node cross?
- 9
- 10
- 31
- 999
Show the answer
A. 9
Each light edge more than doubles the subtree size on the way up, so and . The path then meets at most 10 heavy paths, so a path query uses at most ranges.
Why does every heavy path occupy consecutive positions in the array?
- The segment tree sorts the nodes of each heavy path
- Positions come from a preorder that visits each node's heavy child immediately after the node
- Heavy paths are numbered in order of their heads' depths
- Light edges are given the largest positions
Show the answer
B. Positions come from a preorder that visits each node's heavy child immediately after the node
In a preorder that always goes to the heavy child first, the heavy child's position is its parent's plus one, so a heavy path is a run of consecutive positions. The same preorder also keeps every subtree contiguous.
Removing a centroid from a tree with 101 vertices leaves components of at most how many vertices?
- 33
- 51
- 50
- 100
Show the answer
C. 50
Each component has at most vertices, so at most 50. Below the top level, a centroid decomposition of 101 vertices therefore has components of at most 50, 25, 12, 6, 3 and 1 vertices: levels in all.
In centroid-decomposition pair counting, why is every pair of vertices counted exactly once?
- It is counted at every level, and the total is divided by the number of levels
- Only pairs that contain a centroid are counted
- The distance lists are deduplicated before counting
- Its path stays inside one component until one of its vertices is removed; it is counted at that centroid, and pairs inside one piece are subtracted there
Show the answer
D. Its path stays inside one component until one of its vertices is removed; it is counted at that centroid, and pairs inside one piece are subtracted there
Every path lies in the component of the first of its vertices to be removed and passes through that centroid, so the pair is counted there with its true distance. Pairs inside one piece of that component have paths that avoid the centroid, so their sum of distances overstates the truth; they are subtracted and counted correctly deeper in the recursion.
Further reading
- D. D. Sleator & R. E. Tarjan, "A data structure for dynamic trees," Journal of Computer and System Sciences 26(3) (1983), 362–391.
- D. D. Sleator & R. E. Tarjan, "Self-adjusting binary search trees," Journal of the ACM 32(3) (1985), 652–686.
- S. Alstrup, J. Holm, K. de Lichtenberg & M. Thorup, "Maintaining information in fully dynamic trees with top trees," ACM Transactions on Algorithms (2005).
- M. Pătraşcu & E. D. Demaine, "Logarithmic lower bounds in the cell-probe model," SIAM Journal on Computing (2006).
- CP-Algorithms, "Heavy-light decomposition," cp-algorithms.com.