Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 834 Sum of Distances in Tree - Walkthrough

Tracing rerooting

Compute sum of distances from each node to all others. Naive: O(n2)O(n^2). Rerooting: O(n)O(n). Pass 11 (post-order): compute subtreeSize[v]subtreeSize[v] and subtreeSum[v]subtreeSum[v] = sum of distances within subtree rooted at vv. Pass 22 (pre-order): for each node, combine subtree answer with "rest of tree" answer from parent.

When moving root from uu to child vv: nodes in vv's subtree get 1 closer (there are size[v]size[v]), nodes outside get 1 farther (there are nsize[v]n - size[v]). New answer = old ±\pm difference.