Graphs · Pattern 12 of 14

Re-rooting DP: the answer for every root in O(n)

Solve the problem for one root with a DFS. Then move the root across one edge at a time: only that edge changes, so each neighbour's answer comes from its parent's in O(1).

2 variations · 2 problems

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • A tree, and an answer is wanted for every node as the root
  • Running one DFS per node would be O(n²)
  • Moving the root one step changes the answer by a simple amount

The template

Re-rooting DP
int[] sumOfDistancesInTree(int n, int[][] edges) {
    List<List<Integer>> adj = new ArrayList<>();
    for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
    for (int[] e : edges) { adj.get(e[0]).add(e[1]); adj.get(e[1]).add(e[0]); }
    int[] parent = new int[n], order = new int[n], size = new int[n], ans = new int[n];
    parent[0] = -1;
    for (int head = 0, tail = 1; head < tail; head++) {      // BFS from 0: parents before children
        int u = order[head];
        for (int v : adj.get(u)) if (v != parent[u]) { parent[v] = u; order[tail++] = v; }
    }
    for (int i = n - 1; i >= 0; i--) {                        // children first
        int u = order[i];
        size[u] += 1;
        if (u != 0) { size[parent[u]] += size[u]; ans[0] += size[u]; }   // the edge up is crossed size[u] times
    }
    for (int i = 1; i < n; i++) {                             // parents first: move the root down one edge
        int u = order[i];
        ans[u] = ans[parent[u]] + n - 2 * size[u];           // size[u] nodes get closer, n - size[u] farther
    }
    return ans;
}

The variations

  1. 1Sum over all nodes

    First pass: subtree sizes and the total distance from the root. Moving the root from p to child u brings size[u] nodes one step closer and pushes the other n − size[u] one step farther: ans[u] = ans[p] + n − 2·size[u].

  2. 2Edge costs that flip with direction

    Give each tree edge cost 0 along its direction and 1 against it. Count the reversals needed from node 0, then moving the root across an edge changes the total by +1 or −1, depending on which way that edge points.

Mistakes to avoid

  • Running a full DFS from every node: correct but O(n²), too slow for 10^5 nodes.
  • Recursing on a tree that can be a long path: 10^5 levels overflow the stack. A BFS order, used forwards and backwards, does both passes without recursion.
Next: Minimum spanning tree: Kruskal's algorithm →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.