Graph Theory37 sections · 1633 units
Open in Course

Down Pass (Subtree distances)

(Subtree sums)

Pick node 11 as root. For each node vv, compute down[v] = sum of distances from vv to all nodes in its subtree. Also track size[v] = number of nodes in subtree of vv. Recurrence: down[v] = Σ_(u in children(v)) (down[u] + size[u]). The down[u] part is the sum within uu's subtree. The +size[u] part accounts for the extra edge from vv to uu for each of the size[u] nodes. After this pass, down[1] equals the answer when node 11 is root.

But you need answers for all other roots. That requires the up pass.