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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy