-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsum-of-distances-in-tree.py
30 lines (25 loc) · 1.01 KB
/
sum-of-distances-in-tree.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
class Solution:
def sumOfDistancesInTree(self, N: int, edges: List[List[int]]) -> List[int]:
tree = [[] for _ in range(N)]
for node, child in edges:
tree[node].append(child)
tree[child].append(node)
depth = [0 for _ in range(N)]
count = [0 for _ in range(N)]
def dfs_for_depth_and_count(node, parent):
count[node] = 1
for child in tree[node]:
if child != parent:
depth[child] = depth[node] + 1
dfs_for_depth_and_count(child, node)
count[node] += count[child]
dfs_for_depth_and_count(0, -1)
answer = [0 for _ in range(N)]
answer[0] = sum(depth)
def dfs_for_answer(node, parent):
for child in tree[node]:
if child != parent:
answer[child] = answer[node] + N - 2 * count[child]
dfs_for_answer(child, node)
dfs_for_answer(0, -1)
return answer