Centroid decomposition
Advanced · 12 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Centroid decomposition repeatedly picks the "balance point" of a tree, removes it to split the tree into smaller balanced pieces, and repeats. Because the pieces shrink fast, every node belongs to only a few levels, making path questions affordable.
Practical use cases
- Web app: Nearest open pharmacy on a road tree. A delivery app with a tree-like road network marks stores as open or closed during the day. For each customer it must find the closest open store. Using balance points, each update and each lookup touches only a few levels, so results stay instant.
- Web app: Nearest available driver in a tree-shaped region. A rural delivery service has routes branching like a tree, and drivers go online and offline. With balance points, each lookup of the nearest online driver stays fast, so dispatchers see the closest driver straight away even with thousands of road junctions.
- Web app: Counting connections of a given length. A referral tree needs to know how many pairs of users are exactly 3 referrals apart. Handling each balanced piece once avoids checking every pair of users, so the count appears instantly.
- System: Distance queries and contests. Network analysis tools and contest problems use this to count paths or find the closest marked node on large trees. Every query touches only a handful of balance points, so the work stays small even as the tree grows.
The story: The Mela Committee Chair
The mohalla's lanes formed a tree, and the festival committee wanted to put a water stall where everyone could reach it easily. Zoya suggested trying the junction nearest to the mela ground. But from there, one side of the neighbourhood was huge and the other tiny. Half the people still had a long walk.
"Pick the stall," said Grandpa Bhaskar, "such that if you cross it off, no remaining group is bigger than half of the whole neighbourhood." Zoya tried a few stalls and found one. It always exists in any tree.
The committee then did the same inside each remaining group: find its balanced stall, cross it off, split again. Soon every stall had been a "chair" for some group, and the groups formed a neat family of nested committees only log n levels deep.
Such a stall is a centroid, and splitting a tree by repeatedly removing centroids is centroid decomposition. Any route between two stalls passes through one common committee chair, which makes counting routes much easier.
How to spot this problem, and where you need it
You have a big tree and need to count paths with some property or find the nearest marked node, with marks changing, and checking all pairs or doing a full search each time is too slow.
Signs you need it
- Questions are about distances or counts of paths in a tree with tens of thousands of nodes.
- A search from each query node takes too long, and nodes toggle between marked and unmarked.
- Every path in the tree must pass through some node you could use as a meeting point.
Where to use it in a project
- Finding the nearest open store, driver or service point on a tree-shaped road or network.
- Counting user pairs in a referral or hierarchy tree that are a given distance apart.
- Tree analytics where nodes are switched on and off and the answer must stay up to date.
The solution
Find the centroid, the node whose removal leaves no piece bigger than half the tree. Handle every path that goes through the centroid, using distances from it. Then remove it and repeat inside each smaller piece. Each node sits in only about 17 pieces for 100,000 nodes, so each update or query visits only those few centroids and combines their stored distances.
Payoff: Before: a full search of up to 100,000 nodes per query. After: about 17 small checks.
Explain it like I am 8
Imagine a see-saw with many kids on a long plank. The centroid is the pivot point where neither side is heavier than half. Take the pivot out and you get balanced piles. Do the same to each pile and you end up with tiny balanced groups.
How it works, step by step
- Measure the size of every subtree in the current (not yet removed) piece.
- Find the centroid: walk from any node toward a child whose subtree is bigger than half of the piece, until none is.
- Remove the centroid (mark it removed) and remember who its parent in the centroid tree is.
- Recurse into every remaining piece and repeat from step 1.
- Since every piece is at most half the size, the depth is only log n. Any path between two nodes goes through their lowest common centroid.
The code in four languages
PHP
<?php
// Centroid decomposition: print each node's parent and level in the centroid tree.
$n = 8;
$edges = [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [4, 8]];
$adj = array_fill(0, $n + 1, []);
foreach ($edges as [$a, $b]) { $adj[$a][] = $b; $adj[$b][] = $a; }
$removed = array_fill(0, $n + 1, false);
$size = array_fill(0, $n + 1, 0);
$cpar = array_fill(0, $n + 1, 0); // parent in the centroid tree (0 = root)
$level = array_fill(0, $n + 1, 0);
function calcSize(int $u, int $p): void { // how big is each subtree in this piece?
global $adj, $removed, $size;
$size[$u] = 1;
foreach ($adj[$u] as $v) {
if ($v !== $p && !$removed[$v]) { calcSize($v, $u); $size[$u] += $size[$v]; }
}
}
function findCentroid(int $u, int $p, int $total): int {
global $adj, $removed, $size;
foreach ($adj[$u] as $v) {
if ($v !== $p && !$removed[$v] && $size[$v] * 2 > $total) {
return findCentroid($v, $u, $total); // a child holds more than half: go there
}
}
return $u; // nothing is too big: this is the centroid
}
function decompose(int $u, int $par, int $lvl): void {
global $adj, $removed, $size, $cpar, $level;
calcSize($u, 0);
$c = findCentroid($u, 0, $size[$u]);
$cpar[$c] = $par; $level[$c] = $lvl;
$removed[$c] = true; // cross the centroid off
foreach ($adj[$c] as $v) {
if (!$removed[$v]) decompose($v, $c, $lvl + 1); // each remaining piece
}
}
decompose(1, 0, 0);
for ($v = 1; $v <= $n; $v++) echo "node $v: parent {$cpar[$v]}, level {$level[$v]}\n";JavaScript
// Centroid decomposition: print each node's parent and level in the centroid tree.
const n = 8;
const edges = [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [4, 8]];
const adj = Array.from({ length: n + 1 }, () => []);
for (const [a, b] of edges) { adj[a].push(b); adj[b].push(a); }
const removed = new Array(n + 1).fill(false);
const size = new Array(n + 1).fill(0);
const cpar = new Array(n + 1).fill(0); // parent in the centroid tree (0 = root)
const level = new Array(n + 1).fill(0);
function calcSize(u, p) { // how big is each subtree in this piece?
size[u] = 1;
for (const v of adj[u]) {
if (v !== p && !removed[v]) { calcSize(v, u); size[u] += size[v]; }
}
}
function findCentroid(u, p, total) {
for (const v of adj[u]) {
if (v !== p && !removed[v] && size[v] * 2 > total) {
return findCentroid(v, u, total); // a child holds more than half: go there
}
}
return u; // nothing is too big: this is the centroid
}
function decompose(u, par, lvl) {
calcSize(u, 0);
const c = findCentroid(u, 0, size[u]);
cpar[c] = par; level[c] = lvl;
removed[c] = true; // cross the centroid off
for (const v of adj[c]) {
if (!removed[v]) decompose(v, c, lvl + 1); // each remaining piece
}
}
decompose(1, 0, 0);
for (let v = 1; v <= n; v++) console.log('node ' + v + ': parent ' + cpar[v] + ', level ' + level[v]);Java
import java.util.*;
public class Main {
static int n = 8;
static List<List<Integer>> adj = new ArrayList<>();
static boolean[] removed = new boolean[n + 1];
static int[] size = new int[n + 1];
static int[] cpar = new int[n + 1]; // parent in the centroid tree (0 = root)
static int[] level = new int[n + 1];
static void calcSize(int u, int p) { // how big is each subtree in this piece?
size[u] = 1;
for (int v : adj.get(u)) {
if (v != p && !removed[v]) { calcSize(v, u); size[u] += size[v]; }
}
}
static int findCentroid(int u, int p, int total) {
for (int v : adj.get(u)) {
if (v != p && !removed[v] && size[v] * 2 > total) {
return findCentroid(v, u, total); // a child holds more than half: go there
}
}
return u; // nothing is too big: this is the centroid
}
static void decompose(int u, int par, int lvl) {
calcSize(u, 0);
int c = findCentroid(u, 0, size[u]);
cpar[c] = par;
level[c] = lvl;
removed[c] = true; // cross the centroid off
for (int v : adj.get(c)) {
if (!removed[v]) decompose(v, c, lvl + 1); // each remaining piece
}
}
public static void main(String[] args) {
// Centroid decomposition: print each node's parent and level in the centroid tree.
int[][] edges = {{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {6, 7}, {4, 8}};
for (int i = 0; i <= n; i++) adj.add(new ArrayList<>());
for (int[] e : edges) { adj.get(e[0]).add(e[1]); adj.get(e[1]).add(e[0]); }
decompose(1, 0, 0);
for (int v = 1; v <= n; v++) {
System.out.println("node " + v + ": parent " + cpar[v] + ", level " + level[v]);
}
}
}Go
package main
import "fmt"
const n = 8
var (
adj = make([][]int, n+1)
removed = make([]bool, n+1)
size = make([]int, n+1)
cpar = make([]int, n+1) // parent in the centroid tree (0 = root)
level = make([]int, n+1)
)
func calcSize(u, p int) { // how big is each subtree in this piece?
size[u] = 1
for _, v := range adj[u] {
if v != p && !removed[v] {
calcSize(v, u)
size[u] += size[v]
}
}
}
func findCentroid(u, p, total int) int {
for _, v := range adj[u] {
if v != p && !removed[v] && size[v]*2 > total {
return findCentroid(v, u, total) // a child holds more than half: go there
}
}
return u // nothing is too big: this is the centroid
}
func decompose(u, par, lvl int) {
calcSize(u, 0)
c := findCentroid(u, 0, size[u])
cpar[c], level[c] = par, lvl
removed[c] = true // cross the centroid off
for _, v := range adj[c] {
if !removed[v] {
decompose(v, c, lvl+1) // each remaining piece
}
}
}
func main() {
// Centroid decomposition: print each node's parent and level in the centroid tree.
edges := [][2]int{{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {6, 7}, {4, 8}}
for _, e := range edges {
adj[e[0]] = append(adj[e[0]], e[1])
adj[e[1]] = append(adj[e[1]], e[0])
}
decompose(1, 0, 0)
for v := 1; v <= n; v++ {
fmt.Printf("node %d: parent %d, level %d\n", v, cpar[v], level[v])
}
}Time: O(n log n) · Extra space: O(n). Each level of the centroid tree touches every node once, and there are only about log n levels.
Watch out for
- Forgetting to skip removed nodes when measuring sizes, so pieces leak into each other.
- Re-measuring sizes from the wrong root. Always compute sizes from the node you start the piece with, then compare against that piece's total.
- Mixing up the original tree with the centroid tree. Parents in the centroid tree are not neighbours in the original tree.
Quick check
- What defines a centroid?
- A node whose removal leaves pieces of at most half the size
- The deepest node
- The node with the most edges
- How deep is the centroid tree for n nodes?
- About n
- About log n
- About √n
- After removing a centroid, what do we do?
- Stop
- Delete the whole tree
- Repeat on each remaining piece