Graph Theory37 sections · 1633 units
Open in Course

Rerooting with Count (Combinatorial problems)

(Distance histograms)

Some rerooting problems ask you to count nodes or subtrees satisfying a condition. For example: for each root vv, count how many subtrees have an even number of nodes.

The down pass counts valid subtrees in vv's subtree. The up pass adds valid subtrees from outside. The combine function is addition, so this works like sum-of-distances rerooting.

The tricky part: when a subtree's validity depends on its size, and the size changes when you reroot, you need to recompute validity during the up pass. Track enough state in down[v] to make this adjustment in O(1)O(1).