Class Solution
- java.lang.Object
-
- g0801_0900.s0834_sum_of_distances_in_tree.Solution
-
public class Solution extends Object
834 - Sum of Distances in Tree.Hard
There is an undirected connected tree with
nnodes labeled from0ton - 1andn - 1edges.You are given the integer
nand the arrayedgeswhereedges[i] = [ai, bi]indicates that there is an edge between nodesaiandbiin the tree.Return an array
answerof lengthnwhereanswer[i]is the sum of the distances between theithnode in the tree and all other nodes.Example 1:

Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
Output: [8,12,6,10,10,10]
Explanation: The tree is shown above.
We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) equals 1 + 1 + 2 + 2 + 2 = 8.
Hence, answer[0] = 8, and so on.
Example 2:

Input: n = 1, edges = []
Output: [0]
Example 3:

Input: n = 2, edges = [[1,0]]
Output: [1,1]
Constraints:
1 <= n <= 3 * 104edges.length == n - 1edges[i].length == 20 <= ai, bi < nai != bi- The given input represents a valid tree.
-
-
Constructor Summary
Constructors Constructor Description Solution()
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description int[]sumOfDistancesInTree(int n, int[][] edges)
-