Graph Theory37 sections · 1633 units
Open in Course

Reveal - Fixed-Length Paths I

(Why centroid splits the tree)

Centroid Decomposition splits the tree recursively. At each step, find the centroid (the node whose removal leaves no subtree larger than n/2n/2). Count all paths passing through the centroid.

For this problem: count pairs of nodes (one in each subtree of the centroid) whose combined distance to the centroid equals k. Use a frequency map to do this in linear time per level.

Then remove the centroid and recurse on each subtree. There are O(log⁡n)O(\log n) levels, each doing O(n)O(n) work, giving O(nlog⁡n)O(n \log n) total.

Space complexity is O(n)O(n) for the data structures used.