Sum of Distances in Tree - Problem

There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.

You are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

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

Input & Output

Example 1 — Simple Tree
$ Input: n = 4, edges = [[1,0],[1,2],[1,3]]
Output: [6,4,4,4]
💡 Note: Tree looks like: 0-1-2 with 3 also connected to 1. From node 0: distances are [0,1,2,2] sum=5. From node 1: distances are [1,0,1,1] sum=3. Continue for all nodes.
Example 2 — Linear Tree
$ Input: n = 3, edges = [[0,1],[1,2]]
Output: [3,2,3]
💡 Note: Linear tree 0-1-2. From 0: [0,1,2] sum=3. From 1: [1,0,1] sum=2. From 2: [2,1,0] sum=3.
Example 3 — Single Edge
$ Input: n = 2, edges = [[0,1]]
Output: [1,1]
💡 Note: Two nodes connected: 0-1. From each node, distance to other is 1.

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.

Visualization

Tap to expand
Sum of Distances in TreeInput Tree0123edges = [[0,1],[1,2],[1,3]]Distance Sums:Node 0: 1+2+2=5Node 1: 1+1+1=3Node 2: 2+1+2=5Node 3: 2+1+2=5Result: [5,3,5,5]Optimal Solution:Tree DP with RerootingOutput: [5,3,5,5]Each element is sum of distances from that node to all others
Understanding the Visualization
1
Input Tree
Undirected tree with n nodes and n-1 edges
2
Calculate Distances
For each node, find sum of distances to all other nodes
3
Output Array
Array where result[i] = sum of distances from node i
Key Takeaway
🎯 Key Insight: Use rerooting technique to avoid recalculating distances from scratch for each node
Asked in
Google 15 Facebook 12 Amazon 8
89.5K Views
Medium Frequency
~35 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