Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 834 Sum of Distances in Tree - Two Passes

Down then up

Pass 11 (down): Root at node 00. Compute count[v]\text{count}[v] = nodes in vv's subtree, and sum[v]\text{sum}[v] = sum of distances from vv to all nodes in its subtree. count[v]=1+count[child]\text{count}[v] = 1 + \sum \text{count}[\text{child}] and sum[v]=(sum[child]+count[child])\text{sum}[v] = \sum (\text{sum}[\text{child}] + \text{count}[\text{child}]).

Pass 22 (up): Starting from root, propagate answers to children using the formula from the previous unit.

The first pass collects information from leaves to root. The second pass distributes answers from root to leaves.