Graph Theory37 sections · 1633 units
Open in Course

CSES 1133 Tree Distances II - Core Idea

Rerooting DP technique

If you root the tree at node 11, you can compute the sum of distances from node 11 to all others using DFS. That is one answer.

Now how do you compute the answer for node 22 (a child of 11)? When you move the root from 11 to 22, some nodes get closer and some get farther.

Nodes in the subtree of 22 get 11 closer. Nodes outside the subtree of 22 get 11 farther. You can update the sum in O(1)O(1) using this observation.

This is called rerooting DP.