Overview
If you need to find something like "Sum of Distances to all nodes" for EVERY node in a tree, running a DFS from every node takes O(N²). Rerooting DP does it in O(N).
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
An advanced tree DP technique to compute an answer for ALL nodes acting as the root in O(N) time, rather than the naive O(N²).
If you need to find something like "Sum of Distances to all nodes" for EVERY node in a tree, running a DFS from every node takes O(N²). Rerooting DP does it in O(N).
Run a standard post-order DFS starting from an arbitrary root (e.g., node 0). Calculate the answer just for this root, and also compute auxiliary data like subtree sizes.
Run a second, pre-order DFS. When you move the root from node `u` down to its child `v`, you don't recompute from scratch. You just adjust `u`'s answer based on the shift.
When shifting root to `v`, all nodes in `v`'s subtree get 1 step closer (subtract `count[v]`). All other nodes in the tree get 1 step further (add `N - count[v]`).