Tree Distances II

You are given an undirected tree with n nodes labeled from 1 to n.

For each node, compute the sum of distances from that node to all other nodes in the tree.

The distance between two nodes is defined as the number of edges in the shortest path between them.

Return an array where the ith value represents the sum of distances from node i to every other node.

Example 1:

Input: n = 5, edges = [[1,2],[1,3],[3,4],[3,5]]

Output: [6, 9, 5, 8, 8]

Explanation:

  • For node 1: distances to nodes [2,3,4,5] are [1,1,2,2], sum = 6
  • For node 2: distances to nodes [1,3,4,5] are [1,2,3,3], sum = 9
  • For node 3: distances to nodes [1,2,4,5] are [1,2,1,1], sum = 5
  • For node 4: distances to nodes [1,2,3,5] are [2,3,1,2], sum = 8
  • For node 5: distances to nodes [1,2,3,4] are [2,3,1,2], sum = 8

Example 2:

Input: n = 6, edges = [[1,2],[2,3],[3,4],[4,5],[5,6]]

Output: [15, 11, 9, 9, 11, 15]

Explanation:

This tree is a straight path.

  • For node 1: distances to all other nodes are [1,2,3,4,5], sum = 15
  • For node 2: distances to all other nodes are [1,1,2,3,4], sum = 11
  • For node 3: distances to all other nodes are [2,1,1,2,3], sum = 9
  • For node 4: distances to all other nodes are [3,2,1,1,2], sum = 9
  • For node 5: distances to all other nodes are [4,3,2,1,1], sum = 11
  • For node 6: distances to all other nodes are [5,4,3,2,1], sum = 15

Now Your Turn!

Pick the correct output for the given input

Input: n = 4, edges = [[1,2],[2,3],[3,4]]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= n <= 2 * 105
  • edges.length == n - 1
  • edges[i].length == 2
  • 1 <= edges[i][0], edges[i][1] <= n
  • edges represents a valid tree

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
vector<long long> treeDistancesII(int n, vector<vector<int>> &edges) {
// Your code goes here
}
};
Test Case

Input:

Edges
N