Problem · Tree
Sum of Distances in Tree
Learn this problemProblem statement
You are given a connected undirected tree with n nodes numbered from 0 to n - 1. The array edges contains the tree's n - 1 edges.
Return an integer array answer of length n, where answer[u] is the sum of the shortest-path distances from node u to every other node.
Function
sumOfDistancesInTree(n: int, edges: int[][]) → int[]Examples
Example 1
n = 6edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]return = [8,12,6,10,10,10]From node 0, the distances are 0, 1, 1, 2, 2, 2, which sum to 8. Repeating the definition for each root gives the returned array.
Example 2
n = 1edges = []return = [0]The only node has distance 0 to itself.
Constraints
1 <= n <= 30000edges.length = n - 1- Every row of
edgesis[u, v]with0 <= u, v < nandu != v. edgesforms one connected tree.