8000 Added Subtree Size · AllAlgorithms/python@14630fe · GitHub
[go: up one dir, main page]

Skip to content

Commit 14630fe

Browse files
adi0311abranhe
authored andcommitted
Added Subtree Size
1 parent 66c75c6 commit 14630fe

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
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)

0 commit comments

Comments
 (0)
0