Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 14630fe

Browse filesBrowse files
adi0311abranhe
adi0311
authored andcommitted
Added Subtree Size
1 parent 66c75c6 commit 14630fe
Copy full SHA for 14630fe

File tree

1 file changed

+28
-0
lines changed
Filter options

1 file changed

+28
-0
lines changed
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)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.