Compute subtree answers bottom-up, then transfer the whole-tree answer across every edge in a second pass.
Core idea
A postorder pass solves each subtree for one arbitrary root. A preorder pass then moves the root across every edge using a constant-time relation between parent and child answers.
Read the visualization
The first columns accumulate subtree sizes and downward distances. The answer column begins at the original root and spreads outward with the reroot formula.
size
down
ans
0· root
1·L
2·R
3·LL
4·LR
Root the tree once and prepare subtree sizes plus downward distance sums.
19 ans[0] = down[0]; // number one root: root root answer
20dfs2(0, -1);
21return ans;
22}
tree0 root; 1,2 as child; 3,4 as 1 child
targetans[u] = Σ dist(u, ·), all 5 count
1 / 12
Complexity and tradeoffs
Time: O(n). Space: O(n). A local reroot transition turns one rooted result into answers for every possible root.
Invariant: When processing edge parent to child, the parent's whole-tree answer and the child's subtree summary are already complete.
Where it fits
Rerooting computes all-root distance sums, eccentricity-style values, and tree contributions in linear time instead of repeating a traversal from every node.