Practice › Trees
Sum of Distances in a Tree
Hard · Trees · Asked at Google, Amazon, Uber
An undirected tree has n nodes labelled 1 to n. For every node, print the sum of its distances (number of edges) to all other nodes.
Input
First line: n. Next n − 1 lines: u v — an edge.
Output
n numbers — the answer for nodes 1, 2, …, n.
Constraints
- 1 ≤ n ≤ 3 × 10^4
Root the tree at node 1. One post-order pass computes subtree sizes and the answer for the root. Then re-root: moving from a parent p to a child c brings size(c) nodes one step closer and the other n − size(c) one step farther, so ans[c] = ans[p] − size(c) + (n − size(c)).
Example 1
Input
6 1 2 1 3 3 4 3 5 3 6
Output
8 12 6 10 10 10
Example 2
Input
1
Output
0
Hints
- Running a BFS from every node is O(n²).
- Root the tree at node 1 and compute subtree sizes and the answer for the root in one pass.
- Moving the root from p to its child c changes the answer by n − 2 · size(c).
Approach
BFS from node 1 to get a parent array and an order where parents come before children. Going through the order backwards gives subtree sizes; the root's answer is the sum of all depths. Going forwards, each child c gets ans[c] = ans[p] − size(c) + (n − size(c)): the size(c) nodes in c's subtree get one step closer and everyone else one step farther. No recursion is needed, so deep trees are fine.
Complexity: O(n) time · O(n) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<vector<int>> adj(n + 1);
for (int i = 1; i < n; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
vector<int> order = {1}, par(n + 1, 0);
vector<long long> depth(n + 1, 0), size(n + 1, 1), ans(n + 1, 0);
par[1] = -1;
for (size_t h = 0; h < order.size(); h++) {
int u = order[h];
for (int v : adj[u])
if (v != par[u]) {
par[v] = u;
depth[v] = depth[u] + 1;
order.push_back(v);
}
}
for (int h = n - 1; h > 0; h--) size[par[order[h]]] += size[order[h]];
for (int i = 1; i <= n; i++) ans[1] += depth[i];
for (int h = 1; h < n; h++) {
int c = order[h];
ans[c] = ans[par[c]] - size[c] + (n - size[c]);
}
for (int i = 1; i <= n; i++) cout << ans[i] << (i < n ? ' ' : '\n');
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
n = data[0]
adj = [[] for _ in range(n + 1)]
for i in range(n - 1):
u, v = data[1 + 2 * i], data[2 + 2 * i]
adj[u].append(v)
adj[v].append(u)
order = [1]
par = [0] * (n + 1)
depth = [0] * (n + 1)
par[1] = -1
for u in order:
for v in adj[u]:
if v != par[u]:
par[v] = u
depth[v] = depth[u] + 1
order.append(v)
size = [1] * (n + 1)
for u in reversed(order[1:]):
size[par[u]] += size[u]
ans = [0] * (n + 1)
ans[1] = sum(depth)
for c in order[1:]:
ans[c] = ans[par[c]] - size[c] + (n - size[c])
print(*ans[1:])Java solution
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i <= n; i++) adj.add(new ArrayList<>());
for (int i = 1; i < n; i++) {
in.nextToken();
int u = (int) in.nval;
in.nextToken();
int v = (int) in.nval;
adj.get(u).add(v);
adj.get(v).add(u);
}
int[] order = new int[n], par = new int[n + 1];
long[] depth = new long[n + 1], size = new long[n + 1], ans = new long[n + 1];
int len = 0;
order[len++] = 1;
par[1] = -1;
for (int h = 0; h < len; h++) {
int u = order[h];
for (int v : adj.get(u))
if (v != par[u]) {
par[v] = u;
depth[v] = depth[u] + 1;
order[len++] = v;
}
}
Arrays.fill(size, 1);
for (int h = n - 1; h > 0; h--) size[par[order[h]]] += size[order[h]];
for (int i = 1; i <= n; i++) ans[1] += depth[i];
for (int h = 1; h < n; h++) {
int c = order[h];
ans[c] = ans[par[c]] - size[c] + (n - size[c]);
}
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= n; i++) sb.append(ans[i]).append(i < n ? " " : "\n");
System.out.print(sb);
}
}Solve Sum of Distances in a Tree online · All practice problems