Graph Theory37 sections · 1633 units
Open in Course

CSES 1133 Tree Distances II - Walkthrough

Example trace

Tree: edges (11,22), (11,33), (33,44).

First DFS from node 11: size = {11:44, 22:11, 33:22, 44:11}. Sum from node 11: distances are {11:00, 22:11, 33:11, 44:22}, total = 44.

When you reroot from 11 to 33: nodes in 33's subtree (33,44) get 11 closer, nodes outside (11,22) get 11 farther. New sum = 44 - 22 + 22 = 44.

This increment formula lets you compute all nn answers in O(n)O(n) instead of O(n2)O(n^2) naive BFS from each node.