863. Sum of Distances in Tree
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for an array where each element answer[i] is the sum of distances from node i to all other nodes in a given tree. A naive approach would be to run a Breadth-First Search (BFS) or Depth-First Search (DFS) starting from each node i to calculate all distances and sum them up. This would result in an O(N²) time complexity. Given the constraint n <= 3 * 10^4, an O(N²) solution would be too slow. We need a more efficient linear-time algorithm, likely O(N).
Solution
Sum of Distances in Tree in Python
class Solution:
def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:
# Adjacency list representation of the tree
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
# count[i]: number of nodes in the subtree rooted at i
# ans[i]: sum of distances from node i to all other nodes
count = [1] * n
ans = [0] * n
# First DFS (post-order traversal)
# This computes count[i] for all i
# and ans[i] as sum of distances to nodes in its own subtree
def dfs1(u, p):
for v in adj[u]:
if v == p:
continue
dfs1(v, u)
count[u] += count[v]
ans[u] += ans[v] + count[v]
# Second DFS (pre-order traversal)
# This computes the final ans[i] for all i
# using the parent's final answer
def dfs2(u, p):
for v in adj[u]:
if v == p:
continue
# When we move root from parent u to child v:
# All nodes in v's subtree get 1 unit closer.
# All other (n - count[v]) nodes get 1 unit farther.
ans[v] = ans[u] - count[v] + (n - count[v])
dfs2(v, u)
# Run DFS from an arbitrary root, say 0
dfs1(0, -1)
dfs2(0, -1)
return ans
Sum of Distances in Tree in Java
class Solution {
private List<List<Integer>> adj;
private int[] count;
private int[] ans;
private int n;
public int[] sumOfDistancesInTree(int n, int[][] edges) {
this.n = n;
this.adj = new ArrayList<>();
for (int i = 0; i < n; i++) {
adj.add(new ArrayList<>());
}
for (int[] edge : edges) {
adj.get(edge[0]).add(edge[1]);
adj.get(edge[1]).add(edge[0]);
}
this.count = new int[n];
this.ans = new int[n];
Arrays.fill(count, 1);
// First DFS: post-order traversal to calculate subtree sizes and sum of distances within subtrees.
dfs1(0, -1);
// Second DFS: pre-order traversal to calculate the final answers for all nodes.
dfs2(0, -1);
return ans;
}
// Post-order traversal to calculate subtree sizes and partial sum of distances.
private void dfs1(int u, int p) {
for (int v : adj.get(u)) {
if (v == p) continue;
dfs1(v, u);
count[u] += count[v];
// ans[u] accumulates sum of distances from u to nodes in its subtree.
// ans[v] is sum of distances from v to its subtree.
// To get sum of distances from u to v's subtree, we add 1 for each node in v's subtree.
ans[u] += ans[v] + count[v];
}
}
// Pre-order traversal to update answers for all nodes based on their parent's answer.
private void dfs2(int u, int p) {
for (int v : adj.get(u)) {
if (v == p) continue;
// Calculate ans[v] from ans[u].
// When moving root from parent u to child v:
// Nodes in v's subtree get 1 unit closer.
// Nodes not in v's subtree get 1 unit farther.
ans[v] = ans[u] - count[v] + (n - count[v]);
dfs2(v, u);
}
}
}
Sum of Distances in Tree in C++
class Solution {
public:
vector<int> ans, count;
vector<vector<int>> adj;
int N;
vector<int> sumOfDistancesInTree(int n, vector<vector<int>>& edges) {
N = n;
adj.resize(N);
ans.assign(N, 0);
count.assign(N, 1);
for (auto& edge : edges) {
adj[edge[0]].push_back(edge[1]);
adj[edge[1]].push_back(edge[0]);
}
// First DFS: post-order traversal to calculate count and ans for subtrees
dfs1(0, -1);
// Second DFS: pre-order traversal to calculate final answers for all nodes
dfs2(0, -1);
return ans;
}
// Post-order traversal to calculate subtree sizes and sum of distances in subtrees.
void dfs1(int u, int p) {
for (int v : adj[u]) {
if (v == p) continue;
dfs1(v, u);
// Aggregate information from child v
count[u] += count[v];
// ans[u] accumulates sum of distances from u to nodes in its subtree.
// ans[v] is sum of distances from v to its subtree.
// To get sum of distances from u to v's subtree, we add 1 for each node in v's subtree.
ans[u] += ans[v] + count[v];
}
}
// Pre-order traversal to update answers for all nodes based on parent's answer.
void dfs2(int u, int p) {
for (int v : adj[u]) {
if (v == p) continue;
// Calculate ans[v] from ans[u].
// ans[u] - (ans[v] + count[v]) is the sum of distances from u to nodes outside v's subtree.
// When moving from u to v, all nodes in v's subtree get 1 unit closer.
// All other N - count[v] nodes get 1 unit farther.
ans[v] = ans[u] - count[v] + (N - count[v]);
dfs2(v, u);
}
}
};
Sum of Distances in Tree in TypeScript
function sumOfDistancesInTree(n: number, edges: number[][]): number[] {
const adj: number[][] = Array.from({ length: n }, () => []);
for (const [u, v] of edges) {
adj[u].push(v);
adj[v].push(u);
}
const count: number[] = new Array(n).fill(1);
const ans: number[] = new Array(n).fill(0);
// First DFS (post-order traversal)
// This computes count[i] for all i
// and ans[i] as sum of distances to nodes in its own subtree
const dfs1 = (u: number, p: number) => {
for (const v of adj[u]) {
if (v === p) continue;
dfs1(v, u);
count[u] += count[v];
ans[u] += ans[v] + count[v];
}
};
// Second DFS (pre-order traversal)
// This computes the final ans[i] for all i
// using the parent's final answer
const dfs2 = (u: number, p: number) => {
for (const v of adj[u]) {
if (v === p) continue;
// When we move root from parent u to child v:
// All nodes in v's subtree get 1 unit closer.
// All other (n - count[v]) nodes get 1 unit farther.
ans[v] = ans[u] - count[v] + (n - count[v]);
dfs2(v, u);
}
};
// Run DFS from an arbitrary root, say 0
dfs1(0, -1);
dfs2(0, -1);
return ans;
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.