A tree is one of the simplest data structures: nodes connected by edges, no cycles, a unique path between every pair of nodes. Trees turn up everywhere — file systems, family pedigrees, parse trees in compilers, phylogenetic trees in biology.
Now ask a natural question: how many paths in the tree have exactly length ? A path here is any sequence of distinct adjacent nodes. The naive answer visits every pair of nodes and measures the distance between them — work, which becomes painfully slow the moment climbs into the millions.
The clever answer is centroid decomposition, a divide-and-conquer technique that cuts the tree at precisely the right node and lets you count every path in time. The key insight is deceptively simple: every path either passes through the centroid of the current tree, or it lives entirely in one of the smaller subtrees left after you remove it. Solve the first kind, recurse on the second.
Comments
Loading comments...