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 , which is too slow for .
The rerooting technique solves this in . 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.