You are given an undirected tree with n nodes labeled 0..n-1 and a list of n-1 edges. The tree is connected and contains no cycles.
For each node i, compute:
where dist(i, j) is the number of edges on the unique path between nodes i and j.
n
edges
, where each element is a pair
[u, v]
indicating an undirected edge between
u
and
v
ans
of length
n
, where
ans[i]
is the sum of distances from node
i
to all nodes.
1 ≤ n ≤ 2 * 10^5
edges.length = n - 1
0 ≤ u, v < n
Input:
n = 4
edges = [[0,1],[1,2],[1,3]]
Output:
ans = [5,3,5,5]
Explanation:
1
: distances to
[0,2,3]
are
[1,1,1]
, sum is
3
.
0
: distances to
[1,2,3]
are
[1,2,2]
, sum is
5
.