Skip to content

Commit 9a67ec3

Browse files
committed
Create sum-of-distances-in-tree.py
1 parent e23be42 commit 9a67ec3

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Python/sum-of-distances-in-tree.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
# An undirected, connected tree with N nodes
5+
# labelled 0...N-1 and N-1 edges are given.
6+
#
7+
# The ith edge connects nodes edges[i][0] and edges[i][1] together.
8+
#
9+
# Return a list ans, where ans[i] is the sum of the distances
10+
# between node i and all other nodes.
11+
#
12+
# Example 1:
13+
#
14+
# Input: N = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]
15+
# Output: [8,12,6,10,10,10]
16+
# Explanation:
17+
# Here is a diagram of the given tree:
18+
# 0
19+
# / \
20+
# 1 2
21+
# /|\
22+
# 3 4 5
23+
# We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)
24+
# equals 1 + 1 + 2 + 2 + 2 = 8. Hence, answer[0] = 8, and so on.
25+
# Note: 1 <= N <= 10000
26+
27+
import collections
28+
29+
30+
class Solution(object):
31+
def sumOfDistancesInTree(self, N, edges):
32+
"""
33+
:type N: int
34+
:type edges: List[List[int]]
35+
:rtype: List[int]
36+
"""
37+
def dfs(graph, node, parent, count, result):
38+
for nei in graph[node]:
39+
if nei != parent:
40+
dfs(graph, nei, node, count, result)
41+
count[node] += count[nei]
42+
result[node] += result[nei] + count[nei]
43+
44+
def dfs2(graph, node, parent, count, result):
45+
for nei in graph[node]:
46+
if nei != parent:
47+
result[nei] = result[node] - count[nei] + \
48+
len(count) - count[nei]
49+
dfs2(graph, nei, node, count, result)
50+
51+
graph = collections.defaultdict(list)
52+
for u, v in edges:
53+
graph[u].append(v)
54+
graph[v].append(u)
55+
56+
count = [1] * N
57+
result = [0] * N
58+
59+
dfs(graph, 0, None, count, result)
60+
dfs2(graph, 0, None, count, result)
61+
return result

0 commit comments

Comments
 (0)