Graph Theory37 sections · 1633 units
Open in Course

Rerooting Template (General pattern)

(Apply to any problem)

The rerooting technique follows a two-phase pattern that turns O(n2)O(n^2) brute force into O(n)O(n).

Phase 11: Root the tree at any node (say node 11). Run DFS to compute "downward" DP values for all nodes. Each dp_down[v] answers the question from vv's perspective when vv looks down into its subtree.

Phase 22: Run another DFS to compute "upward" contributions. Each dp_up[v] captures what vv would see if it looked up toward the rest of the tree.

The Core idea is that when you reroot from parent pp to child cc, the subtree rooted at pp (excluding cc) becomes part of cc's upward view. You compute this contribution incrementally instead of re-running the entire DFS.

function reroot(tree)
    dfs_down(1, -1) // Phase 1
    dfs_up(1, -1, 0) // Phase 2
    for each node v
        answer[v] := combine(dp_down[v], dp_up[v])

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