Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

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 O(log⁡n)O(\log n) 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 log⁡2n\log_2 n light edges.
  • Lay heavy paths out contiguously, and answer path queries with at most 2⌈log⁡2n⌉−12\lceil\log_2 n\rceil-1 segment-tree ranges, O(log⁡2n)O(\log^2 n) 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 ⌊log⁡2n⌋+1\lfloor\log_2 n\rfloor+1 levels in O(nlog⁡n)O(n\log n) 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 Ω(log⁡n)\Omega(\log n) cell-probe lower bound.

Heavy and light edges

DerivationProof
  1. size⁡(p) ≥ 1+size⁡(h)+size⁡(c) > 2size⁡(c)\operatorname{size}(p)\ \ge\ 1+\operatorname{size}(h)+\operatorname{size}(c)\ >\ 2\operatorname{size}(c)

    A light edge more than doubles the size. If (p,c)(p,c) is light, pp has a heavy child h≠ch\ne c with size⁡(h)≥size⁡(c)\operatorname{size}(h)\ge\operatorname{size}(c):

  2. n ≥ size⁡(root) > 2ksize⁡(v) ≥ 2k⟹k<log⁡2nn\ \ge\ \operatorname{size}(\text{root})\ >\ 2^k\operatorname{size}(v)\ \ge\ 2^k\quad\Longrightarrow\quad k<\log_2 n

    Climb to the root. Subtree sizes never decrease on the way up, and each light edge more than doubles them. After kk light edges:

  3. n=2h+1−1⟹k=h=log⁡2(n+1)−1n=2^{h+1}-1\quad\Longrightarrow\quad k=h=\log_2(n+1)-1

    Heavy paths. Between consecutive light edges the climb stays on one heavy path, so it meets k+1≤⌈log⁡2n⌉k+1\le\lceil\log_2 n\rceil of them. The bound is tight: in a perfect binary tree of height hh, always stepping to the light child crosses hh light edges.

Sleator and Tarjan (1983) introduced the partition for their dynamic trees, calling the edge from vv to its parent heavy when 2size⁡(v)>size⁡(parent)2\operatorname{size}(v)>\operatorname{size}(\text{parent}). 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 log⁡2n\log_2 n 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 vv occupies exactly [pos⁡(v),pos⁡(v)+size⁡(v)−1]\big[\operatorname{pos}(v),\operatorname{pos}(v)+\operatorname{size}(v)-1\big].

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 uu–vv: while uu and vv 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.

cpp
#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 [pos⁡(u)+1,pos⁡(v)][\operatorname{pos}(u)+1,\operatorname{pos}(v)] 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.

text
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  3

A 14-node tree; ═ marks heavy edges. Subtree sizes: AA 14, BB 7, CC 6, DD 4, FF 3, and so on, so BB, DD, HH, FF and KK are heavy children.

Check your understanding

In the same tree, into how many ranges does the procedure split the path from II to MM?

  1. 2
  2. 3
  3. 4
  4. 7
Show the answer

C. 4

II is a heavy path by itself (position 5); then GG–MM (12–13); then CC alone (8), because CC's heavy path continues down through FF, KK, LL, which are not on this path; finally AA–DD (0–2). Four ranges cover the seven nodes I,D,B,A,C,G,MI,D,B,A,C,G,M, with sum 2+9+7+11=292+9+7+11=29.

Centroids

DerivationProof
  1. ∣{component of T−w containing v}∣=n−∣B∣ < n2\big|\{\text{component of }T-w\text{ containing }v\}\big|=n-|B|\ <\ \tfrac n2

    Walk downhill. Start at any vertex vv. If some component BB of T−vT-v has more than n/2n/2 vertices, step to vv's neighbor ww in BB. The component of T−wT-w that contains vv is everything outside BB:

  2. max⁡(n−size⁡(v), max⁡c child of vsize⁡(c)) ≤ n2\max\Big(n-\operatorname{size}(v),\ \max_{c\text{ child of }v}\operatorname{size}(c)\Big)\ \le\ \tfrac n2

    So the walk never steps back, visits each vertex at most once, and stops at a vertex all of whose components have at most n/2n/2 vertices: a centroid. With subtree sizes computed once from any root, testing a vertex costs O(deg⁡v)O(\deg v), so O(n)O(n) in all.

  3. n=∣A∪B∣ ≤ ∣A∣+∣B∣ ≤ n⟹A∩B=∅,  ∣A∣=∣B∣=n2n=|A\cup B|\ \le\ |A|+|B|\ \le\ n\quad\Longrightarrow\quad A\cap B=\varnothing,\ \ |A|=|B|=\tfrac n2

    At most two, and adjacent. Let c1≠c2c_1\ne c_2 be centroids, AA the component of T−c1T-c_1 containing c2c_2, and BB the component of T−c2T-c_2 containing c1c_1. Every vertex lies in AA or in BB, and both have at most n/2n/2 vertices:

  4. c1c2∈E(T)c_1c_2\in E(T)

    A vertex strictly between c1c_1 and c2c_2 would lie in both AA and BB, so there is none: c1c_1 and c2c_2 are adjacent, and nn is even. Three centroids would be pairwise adjacent, a triangle, which a tree cannot contain.

Check your understanding

How many centroids does a path of 8 vertices have?

  1. 1, the vertex in the exact middle
  2. 2, the two middle vertices, which are adjacent
  3. 8, since all vertices of a path look alike
  4. 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 8/2=48/2=4. 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 cc, then recurse on each component of T−cT-c. The centroids chosen form the centroid decomposition, a rooted tree of its own with cc at the top and the components' centroids as its children.

DerivationProof
  1. 1 ≤ n2i⟹i ≤ ⌊log⁡2n⌋1\ \le\ \frac{n}{2^i}\quad\Longrightarrow\quad i\ \le\ \lfloor\log_2 n\rfloor

    Levels. Each cut at a centroid at least halves component sizes, so a component at level ii has at most n/2in/2^i vertices, and a nonempty one has at least one:

  2. O(n)⋅(⌊log⁡2n⌋+1)=O(nlog⁡n)O(n)\cdot\big(\lfloor\log_2 n\rfloor+1\big)=O(n\log n)

    Time. The components of one level are disjoint, and their centroids are found in time linear in their sizes, so each level costs O(n)O(n):

  3. P⊆comp⁡(c)andc∈PP\subseteq\operatorname{comp}(c)\qquad\text{and}\qquad c\in P

    Paths. Take a path PP. As long as none of its vertices has been removed, PP stays connected, inside one component. The first vertex of PP to be removed is therefore the centroid cc of that component:

So each of the (n2)\binom{n}{2} pairs of vertices is handled at exactly one centroid. To count the pairs at distance at most KK, list at each centroid cc the distances from cc to all vertices of its component, count the pairs whose two distances sum to at most KK, and subtract the pairs that lie in one piece of the component minus cc: their path avoids cc, so the sum overstates their distance, and they are counted deeper.

text
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 pointers

Each level sorts O(n)O(n) distances: O(nlog⁡2n)O(n\log^2 n) in all. For distance exactly KK, counting arrays replace the sorting and give O(nlog⁡n)O(n\log n). A Python version was checked against breadth-first search from every vertex on 600 random trees; on paths the recursion uses exactly ⌊log⁡2n⌋+1\lfloor\log_2 n\rfloor+1 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 O(log⁡n)O(\log n) paths change per access. With splay trees (Sleator & Tarjan, 1985), every operation (link, cut, find the root, a path aggregate, an LCA) costs O(log⁡n)O(\log n) amortized. Their headline application was maximum flow in O(nmlog⁡n)O(nm\log n) 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 O(log⁡n)O(\log n), 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 O(log⁡n)O(\log n) per operation.

StructureTreePath aggregateSubtree aggregate
Heavy-light + segment treefixed shape, changing valuesO(log⁡2n)O(\log^2 n)O(log⁡n)O(\log n)
Centroid decompositionfixedcounting over all paths; nearest marked vertex in O(log⁡n)O(\log n)not its purpose
Link-cut treelink and cut, O(log⁡n)O(\log n)O(log⁡n)O(\log n)only with an extension
Euler-tour treelink and cut, O(log⁡n)O(\log n)not supportedO(log⁡n)O(\log n)
Top treelink and cut, O(log⁡n)O(\log n)O(log⁡n)O(\log n)O(log⁡n)O(\log n)
For the dynamic structures, the bounds are amortized or worst case depending on the search trees inside them; splay-based versions are amortized.

Key takeaways

  • A heavy edge leads to a child with the largest subtree; every root path crosses fewer than log⁡2n\log_2 n 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 2⌈log⁡2n⌉−12\lceil\log_2 n\rceil-1 ranges, O(log⁡2n)O(\log^2 n) with a segment tree, and subtree queries one range.
  • Every tree has one centroid or two adjacent ones. Removing centroids recursively gives at most ⌊log⁡2n⌋+1\lfloor\log_2 n\rfloor+1 levels in O(nlog⁡n)O(n\log n) 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 O(log⁡n)O(\log n) 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.

Question 1

A rooted tree has 1,000 nodes. At most how many light edges can a path from the root to a node cross?

  1. 9
  2. 10
  3. 31
  4. 999
Show the answer

A. 9

Each light edge more than doubles the subtree size on the way up, so 2k<10002^k<1000 and k≤9k\le9. The path then meets at most 10 heavy paths, so a path query uses at most 2⋅10−1=192\cdot10-1=19 ranges.

Question 2

Why does every heavy path occupy consecutive positions in the array?

  1. The segment tree sorts the nodes of each heavy path
  2. Positions come from a preorder that visits each node's heavy child immediately after the node
  3. Heavy paths are numbered in order of their heads' depths
  4. 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.

Question 3

Removing a centroid from a tree with 101 vertices leaves components of at most how many vertices?

  1. 33
  2. 51
  3. 50
  4. 100
Show the answer

C. 50

Each component has at most 101/2=50.5101/2=50.5 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: ⌊log⁡2101⌋+1=7\lfloor\log_2 101\rfloor+1=7 levels in all.

Question 4

In centroid-decomposition pair counting, why is every pair of vertices counted exactly once?

  1. It is counted at every level, and the total is divided by the number of levels
  2. Only pairs that contain a centroid are counted
  3. The distance lists are deduplicated before counting
  4. 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.