Graph Theory37 sections · 1633 units
Open in Course

Intro

(Why rerooting matters)

You know how to run DFS from a fixed root and compute subtree answers. But what if the problem asks you to compute that answer for every possible root? Running a separate DFS from each node gives O(n2)O(n^2), which is too slow for n=200,000n = 200{,}000.

The rerooting technique solves this in O(n)O(n). You compute the answer for one root, then shift it to every other root by adjusting contributions as you move along edges. I'll walk you through the two-pass algorithm, show you the template, and apply it to problems from CSES and LeetCode.