-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathCountLeafNodes.py
More file actions
42 lines (40 loc) · 1.03 KB
/
CountLeafNodes.py
File metadata and controls
42 lines (40 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import sys
class treeNode:
def __init__(self, data):
self.data = data
self.children = []
def __str__(self):
return str(self.data)
def leafNodeCount(tree):
#############################
# PLEASE ADD YOUR CODE HERE #
#############################
if tree is None:
return 0
childCount = len(tree.children)
if childCount == 0:
return 1
res = 0
for i in range(childCount):
res += leafNodeCount(tree.children[i])
return res
def createLevelWiseTree(arr):
root = treeNode(int(arr[0]))
q = [root]
size = len(arr)
i = 1
while i<size:
parent = q.pop(0)
childCount = int(arr[i])
i += 1
for j in range(0,childCount):
temp = treeNode(int(arr[i+j]))
parent.children.append(temp)
q.append(temp)
i += childCount
return root
# Main
sys.setrecursionlimit(10**6)
arr = list(int(x) for x in input().strip().split(' '))
tree = createLevelWiseTree(arr)
print(leafNodeCount(tree))