Graph Theory37 sections · 1633 units
Open in Course

Up Pass (Parent contribution)

(Outside contributions)

For Tree Distances II, the up pass is simple. You already computed answer[1] = down[1] (the sum of distances from node 11 to all others). Now propagate to children.

For each child vv of uu: answer[v] = answer[u] + n - 2 * size[v]. The - size[v] term accounts for vv's subtree nodes getting closer. The + (n - size[v]) term accounts for outside nodes getting farther. You do not need prefix-suffix arrays here because the combine function is addition. Excluding one child's contribution is just subtraction.

This second DFS runs in O(n)O(n) time and uses O(n)O(n) space.