Skip to problem
←

Sum of Distances in Tree

Hard 0 attempts

Given a connected, undirected tree with n vertices labeled 0 through n - 1, return the sum of distances from each vertex to all other vertices.

Each pair [u,v] in edges is an undirected, unweighted edge. A distance is the number of edges on the unique path between two vertices. This is a general tree, not necessarily a binary tree.

Return an array in vertex-label order: answer[i] is the total for vertex i. The distance from a vertex to itself is zero. A one-vertex tree therefore returns [0].

Function contract

Implement sumOfDistancesInTree(n, edges).

Output: Return n totals in vertex-label order. answer[i] is the sum of edge-count distances from vertex i to every other vertex.

Example 1

Input
n = 6
edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
Output
[8,12,6,10,10,10]

Example 2

Input
n = 1
edges = []
Output
[0]
Constraints
  • 1 <= n <= 3 * 10^4
  • edges.length == n - 1
  • Each edge [u,v] joins distinct labels with 0 <= u,v < n
  • The edges form a connected undirected tree with no cycles

Iterative Rerooting

First build a parent-before-child order. Process it backward to compute subtree sizes and distances from each subtree root. Process it forward to reroot: moving to a child makes its subtree nodes one step closer and all remaining nodes one step farther.

For child u, exactly count[u] vertices become one edge closer when moving the root from its parent to u, while n - count[u] become one edge farther. Therefore answer[u] = answer[parent[u]] + n - 2 × count[u]. The first backward pass establishes the total for vertex 0; the forward pass derives all remaining totals.

javascript
function sumOfDistancesInTree(n, edges) {
  const graph = Array.from({ length: n }, () => []);
  for (const [u, v] of edges) {
    graph[u].push(v);
    graph[v].push(u);
  }
  const parent = Array(n).fill(-1),
    order = [0],
    count = Array(n).fill(1),
    answer = Array(n).fill(0);
  for (let i = 0; i < order.length; i++) {
    const u = order[i];
    for (const v of graph[u])
      if (v !== parent[u]) {
        parent[v] = u;
        order.push(v);
      }
  }
  for (let i = n - 1; i > 0; i--) {
    const u = order[i],
      p = parent[u];
    count[p] += count[u];
    answer[p] += answer[u] + count[u];
  }
  for (let i = 1; i < n; i++) {
    const u = order[i];
    answer[u] = answer[parent[u]] + n - 2 * count[u];
  }
  return answer;
}

Time: O(n) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript