Sum of Distances in Tree - Problem

You are given an undirected connected tree with n nodes labeled from 0 to n - 1 and exactly n - 1 edges. Your task is to calculate the sum of distances from each node to all other nodes in the tree.

Given:

  • An integer n representing the number of nodes
  • An array edges where edges[i] = [a_i, b_i] indicates an edge between nodes a_i and b_i

Goal: Return an array answer of length n where answer[i] is the sum of distances between the i-th node and all other nodes in the tree.

Note: The distance between two nodes is the number of edges in the shortest path between them.

Input & Output

example_1.py — Basic Tree
$ Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
Output: [8,12,6,10,10,10]
💡 Note: Tree looks like: 1-0-2-3,4,5. From node 0: distances are [0,1,1,2,2,2] so sum=8. From node 2: distances are [0,1,2,1,1,1] so sum=6.
example_2.py — Linear Tree
$ Input: n = 3, edges = [[1,0],[2,1]]
Output: [3,2,3]
💡 Note: Linear tree: 0-1-2. From node 0: distances [0,1,2] sum=3. From node 1: distances [1,0,1] sum=2. From node 2: distances [2,1,0] sum=3.
example_3.py — Single Node
$ Input: n = 1, edges = []
Output: [0]
💡 Note: Only one node, so distance sum is 0.

Visualization

Tap to expand
Tree Rerooting TechniqueROOTABCDWhen rerooting from ROOT to A:• Nodes in A's subtree get 1 step closer• All other nodes get 1 step fartherKey Formula:answer[child] = answer[parent] - count[child] + (n - count[child])
Understanding the Visualization
1
Build the Tree
Create adjacency list representation of the tree from given edges
2
First DFS Pass
Calculate subtree sizes and sum of distances from an arbitrary root (node 0)
3
Second DFS Pass
Use rerooting: when moving from parent to child, some nodes get closer, others get farther
4
Mathematical Transform
Apply the formula to efficiently calculate answer for each node
Key Takeaway
🎯 Key Insight: Instead of recalculating distances from scratch for each node, we can mathematically transform the answer from parent to child using subtree size information!

Time & Space Complexity

Time Complexity
⏱️
O(n)

Two DFS passes, each visiting every node exactly once

n
2n
Linear Growth
Space Complexity
O(n)

Space for adjacency list, count array, and recursion stack

n
2n
Linearithmic Space

Constraints

  • 1 ≤ n ≤ 3 × 104
  • edges.length == n - 1
  • edges[i].length == 2
  • 0 ≤ ai, bi < n
  • ai ≠ bi
  • The given input represents a valid tree
Asked in
Google 42 Amazon 28 Meta 35 Microsoft 18
89.7K Views
Medium-High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen