Skip to content

Commit 93fa003

Browse files
committed
Runtime: 1783 ms (Top 30.42%) | Memory: 59.4 MB (Top 95.18%)
1 parent 68f2849 commit 93fa003

File tree

1 file changed

+9
-9
lines changed

1 file changed

+9
-9
lines changed

scripts/algorithms/S/Sum of Distances in Tree/Sum of Distances in Tree.py

+9-9
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1+
# Runtime: 1783 ms (Top 30.42%) | Memory: 59.4 MB (Top 95.18%)
12
from typing import List
23

34
ROOT_PARENT = -1
45

5-
66
class Solution:
77
def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:
88
"""
@@ -11,15 +11,15 @@ def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:
1111
:param edges:
1212
:return:
1313
"""
14-
g = self.create_undirected_graph(edges, n) # as mentioned in the problem, this graph can be converted into tree
14+
g = self.create_undirected_graph(edges, n) # as mentioned in the problem, this graph can be converted into tree
1515

16-
root = 0 # can be taken to any node between 0 and n - 1 (both exclusive)
16+
root = 0 # can be taken to any node between 0 and n - 1 (both exclusive)
1717

1818
# considering "root" as starting node, we create a tree.
1919
# Now defining,
20-
# tree_nodes[i] = number of nodes in the tree rooted at node i
21-
# distances[i] = sum of distances of all nodes from ith node to all the
22-
# other nodes of the tree
20+
# tree_nodes[i] = number of nodes in the tree rooted at node i
21+
# distances[i] = sum of distances of all nodes from ith node to all the
22+
# other nodes of the tree
2323
tree_nodes, distances = [0] * n, [0] * n
2424

2525
def postorder(rt: int, parent: int):
@@ -60,9 +60,9 @@ def preorder(rt: int, parent: int):
6060
for c in g[rt]:
6161
if c != parent:
6262
distances[c] = (
63-
(n - tree_nodes[c]) # rt -> c increase this much distance
63+
(n - tree_nodes[c]) # rt -> c increase this much distance
6464
+
65-
(distances[rt] - tree_nodes[c]) # rt -> c decrease this much distance
65+
(distances[rt] - tree_nodes[c]) # rt -> c decrease this much distance
6666
)
6767
preorder(c, rt)
6868

@@ -85,4 +85,4 @@ def create_undirected_graph(edges: List[List[int]], n: int):
8585
g[u].append(v)
8686
g[v].append(u)
8787

88-
return g
88+
return g

0 commit comments

Comments
 (0)