You are given an undirected tree with n nodes labeled 0 through n - 1, described by an array edges of n - 1 pairs, where edges[i] = [a, b] means nodes a and b are connected.
Return an array answer of length n where answer[i] is the sum of the distances (edge counts) between node i and every other node in the tree.
Examples
Example 1
Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
Output: [8,12,6,10,10,10]
Explanation: From node 0 the distances to nodes 1..5 are 1, 1, 2, 2, 2, so
answer[0] = 8. Node 2 is the most central: 2 + 1 + 1 + 1 + 1 = 6.
Example 2
Input: n = 1, edges = []
Output: [0]
Example 3
Input: n = 2, edges = [[1,0]]
Output: [1,1]
Constraints
1≤n≤3⋅104
edges.length=n−1
0≤a, b<n
The edges form a valid tree.
Loading editor...
Log in to run your code. Your draft is saved in this browser.Log inSign up