25. Sum of Distances in Tree
Hard : IMP
An undirected, connected tree with N
nodes labelled 0...N-1
and N-1
edges
are given.
The i
th edge connects nodes edges[i][0]
and edges[i][1]
together.
Return a list ans
, where ans[i]
is the sum of the distances between node i
and all other nodes.
Example 1:
Solution: (Using Two DFS)
Approach
Solve it with node
0
as root.Initial an array
count
,count[i]
counts all nodes in the subtreei
. Initial an array ofres
,res[i]
counts sum of distance in subtreei
.1st DFS call is similar to basic approach finding the distance and sum of each node from index 0. Update the count and res
count[root] = sum(count[i]) + 1
res[root] = sum(res[i]) + sum(count[i])
2nd DFS is the Dp approach When we move our root from parent to its child
i
,count[i]
points get 1 closer to root,n - count[i]
nodes get 1 further to root.res[i] = res[root] - count[i] + N - count[i]
Last updated