forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0834.py
31 lines (28 loc) · 908 Bytes
/
0834.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import collections
class Solution:
def sumOfDistancesInTree(self, N, edges):
"""
:type N: int
:type edges: List[List[int]]
:rtype: List[int]
"""
graph = collections.defaultdict(set)
for u, v in edges:
graph[u].add(v)
graph[v].add(u)
count = [1] * N
res = [0] * N
def dfs1(node = 0, parent = None):
for child in graph[node]:
if child != parent:
dfs1(child, node)
count[node] += count[child]
res[node] += res[child] + count[child]
def dfs2(node = 0, parent = None):
for child in graph[node]:
if child != parent:
res[child] = res[node] - count[child] + N - count[child]
dfs2(child, node)
dfs1()
dfs2()
return res