Graph Theory37 sections · 1633 units
Open in Course

Rerooting Intuition (Reusing previous work)

(Incremental updates)

Here is the core idea: when you move the root from node uu to its child vv, most of the tree stays the same. Only the edge between uu and vv changes direction. Nodes in vv's subtree get 11 step closer to the new root. Nodes outside vv's subtree get 11 step farther.

You do not need to recompute everything from scratch. You adjust the old answer by a small amount that depends on the subtree size of vv. This incremental update takes O(1)O(1) per edge. Since a tree has n1n - 1 edges, you visit each once and get all nn answers in O(n)O(n) total.