Sum of Distances in Tree
An undirected, connected tree withN
nodes labelled0...N-1
andN-1edges
are given.
Thei
th edge connects nodes edges[i][0]
andedges[i][1]
together.
Return a listans
, whereans[i]
is the sum of the distances between nodei
and all other nodes.
Example 1:
Note:1 <= N <= 10000
分析
count[i] i子树里所有点数,加点个数这里是为了对每个点都推进一个距离。
res[i]答案 ,在第一层post traversal是得到所有子树到该点距离。
第二层pre traversal更新,联系每次向子点推进,子点往下所有儿子距离-1,子点往上所有父点距离+1
前序遍历得到
Last updated