1
+ # Runtime: 1783 ms (Top 30.42%) | Memory: 59.4 MB (Top 95.18%)
1
2
from typing import List
2
3
3
4
ROOT_PARENT = - 1
4
5
5
-
6
6
class Solution :
7
7
def sumOfDistancesInTree (self , n : int , edges : List [List [int ]]) -> List [int ]:
8
8
"""
@@ -11,15 +11,15 @@ def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:
11
11
:param edges:
12
12
:return:
13
13
"""
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
15
15
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)
17
17
18
18
# considering "root" as starting node, we create a tree.
19
19
# 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
23
23
tree_nodes , distances = [0 ] * n , [0 ] * n
24
24
25
25
def postorder (rt : int , parent : int ):
@@ -60,9 +60,9 @@ def preorder(rt: int, parent: int):
60
60
for c in g [rt ]:
61
61
if c != parent :
62
62
distances [c ] = (
63
- (n - tree_nodes [c ]) # rt -> c increase this much distance
63
+ (n - tree_nodes [c ]) # rt -> c increase this much distance
64
64
+
65
- (distances [rt ] - tree_nodes [c ]) # rt -> c decrease this much distance
65
+ (distances [rt ] - tree_nodes [c ]) # rt -> c decrease this much distance
66
66
)
67
67
preorder (c , rt )
68
68
@@ -85,4 +85,4 @@ def create_undirected_graph(edges: List[List[int]], n: int):
85
85
g [u ].append (v )
86
86
g [v ].append (u )
87
87
88
- return g
88
+ return g
0 commit comments