File tree 1 file changed +28
-0
lines changed
Filter options
algorithms/data-structures/trees
1 file changed +28
-0
lines changed
Original file line number Diff line number Diff line change
1
+ """
2
+ This is an efficient algorithm to find the size of a subtree from every node in O(n) time.
3
+ The idea is to use one dfs and first calculate the size of subtree of children of a node recursively.
4
+ Then add the size of each subtree of its children to get the size of its subtree.
5
+ """
6
+ from collections import defaultdict as dd
7
+
8
+
9
+ def dfs (source , parent ):
10
+ # Initial size of root is 1
11
+ size [source ] = 1
12
+ for child in graph [source ]:
13
+ if child != parent :
14
+ # Recursively calculate size of subtree of children nodes
15
+ dfs (child , source )
16
+ # Adding size of each child's subtree.
17
+ size [source ] += size [child ]
18
+
19
+
20
+ size = dd (int )
21
+ graph = dd (set )
22
+ n = int (input ())
23
+ for i in range (n - 1 ):
24
+ u , v = map (int , input ().split ())
25
+ graph [u ].add (v )
26
+ graph [v ].add (u )
27
+ dfs (1 , 0 )
28
+ print (size )
You can’t perform that action at this time.
0 commit comments