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: [5,3,5,5]
💡 Note: Tree looks like: 0-1-2 with 3 also connected to 1. From node 0: distances are [1,2,2] sum=5. From node 1: distances are [1,1,1] sum=3. From node 2: distances are [2,1,2] sum=5. From node 3: distances are [2,1,2] sum=5.
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 Tree INPUT 1 0 2 3 n = 4 edges = [[1,0],[1,2],[1,3]] [1,0] [1,2] [1,3] Star-shaped tree Node 1 is center Find sum of distances from each node to all others ALGORITHM STEPS 1 Build Adjacency List Create graph from edges 2 First DFS (Root at 0) Compute count[] and ans[0] count[i] = subtree size of i count = [1, 4, 1, 1] ans[0] = 6 (1+1+1+3) 3 Second DFS (Reroot) Move root from parent to child Rerooting Formula: ans[child] = ans[parent] - count[child] + (n - count[child]) 4 Calculate All Answers ans[1] = 6 - 4 + 0 = 4 Time: O(n), Space: O(n) Two DFS passes total FINAL RESULT 1 sum=4 0 sum=6 2 sum=4 3 sum=4 Output: [6, 4, 4, 4] Node 0: 1+2+2 = 6 Node 1: 1+1+1+1 = 4 Node 2: 2+1+2 = 4 Node 3: 2+1+2 = 4 OK - Verified! Key Insight: Rerooting technique: When moving root from parent to child, count[child] nodes get 1 closer, while (n - count[child]) nodes get 1 farther. This gives O(n) solution instead of naive O(n^2). Formula: ans[child] = ans[parent] - count[child] + (n - count[child]) = ans[parent] + n - 2*count[child] TutorialsPoint - Sum of Distances in Tree | Tree DP with Rerooting Approach
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