Dynamic Programming21 sections · 916 units
Open in Course

Rerooting Technique

Why rerooting?

Some problems ask: for each node, what's the answer if that node were the root? Naive approach: run tree DP nn times, once per root. That's O(n2)O(n^2). Rerooting does it in O(n)O(n) using two passes.

First, compute answers with an arbitrary root. Then, "move" the root to each neighbor efficiently by adjusting the dp values. When does root choice matter? If dp[node]dp[\text{node}] depends on the direction of parent-child relationships, different roots give different answers.