Graph Theory37 sections · 1633 units
Open in Course

Final Answer (Combining down and up)

(Merge down and up)

For each node vv, the final answer combines two pieces of information.

The down contribution is what you computed when vv was in a subtree during Phase 11. This captures everything below vv.

The up contribution is what comes from the rest of the tree when vv acts as the root during Phase 22. This captures everything above vv.

For tree diameter, the answer at node vv is the maximum depth you can reach going down into any subtree OR going up through the parent and then down into sibling subtrees.

answer[v] := max(dp_down[v], dp_up[v])

This gives you every node's "view" of the tree. You compute all nn answers in O(n)O(n) total time instead of running nn separate DFS traversals. That is the power of rerooting: you reuse information instead of recomputing it.

Space complexity is O(n)O(n) for the data structures used.