Graph Theory37 sections · 1633 units
Open in Course

Combining Down and Up (Final answers)

(Merging results)

After both passes, every node vv has two values. down[v] captures everything in vv's subtree. up[v] captures everything outside vv's subtree. The final answer for node vv as root combines these two.

For sum-of-distances, the formula is answer[v] = down[v] + up[v]. For max-depth problems, it might be answer[v] = max(down[v], up[v]). The combine function depends on the problem, but the two-pass structure stays the same.

This gives you all nn answers in O(n)O(n) total time and O(n)O(n) space. No recomputation needed.