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).
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
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;
} def sum_of_distances_in_tree(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
parent, order = [-1] * n, [0]
for u in order: # BFS from 0: parents before children
for v in adj[u]:
if v != parent[u]:
parent[v] = u
order.append(v)
size, ans = [1] * n, [0] * n
for u in reversed(order[1:]): # children first
size[parent[u]] += size[u]
ans[0] += size[u] # the edge up is crossed size[u] times
for u in order[1:]: # parents first: move the root down one edge
ans[u] = ans[parent[u]] + n - 2 * size[u]
return ans vector<int> sumOfDistancesInTree(int n, vector<vector<int>>& edges) {
vector<vector<int>> adj(n);
for (auto& e : edges) { adj[e[0]].push_back(e[1]); adj[e[1]].push_back(e[0]); }
vector<int> parent(n, -1), order = {0}, size(n, 1), ans(n, 0);
for (int head = 0; head < (int)order.size(); head++) { // BFS from 0: parents before children
int u = order[head];
for (int v : adj[u]) if (v != parent[u]) { parent[v] = u; order.push_back(v); }
}
for (int i = n - 1; i >= 1; i--) { // children first
int u = order[i];
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;
} function sumOfDistancesInTree(n, edges) {
const adj = Array.from({ length: n }, () => []);
for (const [u, v] of edges) { adj[u].push(v); adj[v].push(u); }
const parent = new Array(n).fill(-1), order = [0];
for (let head = 0; head < order.length; head++) { // BFS from 0: parents before children
const u = order[head];
for (const v of adj[u]) if (v !== parent[u]) { parent[v] = u; order.push(v); }
}
const size = new Array(n).fill(1), ans = new Array(n).fill(0);
for (let i = n - 1; i >= 1; i--) { // children first
const u = order[i];
size[parent[u]] += size[u];
ans[0] += size[u]; // the edge up is crossed size[u] times
}
for (let i = 1; i < n; i++) { // parents first: move the root down one edge
const u = order[i];
ans[u] = ans[parent[u]] + n - 2 * size[u];
}
return ans;
} The variations
-
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 othern − size[u]one step farther:ans[u] = ans[p] + n − 2·size[u]. -
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.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.