-
Notifications
You must be signed in to change notification settings - Fork 131
/
Number of Leaf Nodes
38 lines (37 loc) Β· 991 Bytes
/
Number of Leaf Nodes
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
class BinaryTreeNode:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def treeInput():
rootData = int(input())
if rootData == -1:
return None
root = BinaryTreeNode(rootData)
leftTree = treeInput()
rightTree = treeInput()
root.left = leftTree
root.right = rightTree
return root
def PrintTree(root):
if root == None:
return
print(root.data,end= ":")
if root.left is not None:
print("L", root.left.data, end = ",")
if root.right is not None:
print("R", root.right.data, end = "")
print()
PrintTree(root.left)
PrintTree(root.right)
def NumLeafNOdes(root):
if root is None:
return 0
if root.left == None and root.right == None:
return 1
numLeafLeft = NumLeafNOdes(root.left)
numLeafRight = NumLeafNOdes(root.right)
return numLeafLeft + numLeafRight
root = treeInput()
PrintTree(root)
print(NumLeafNOdes(root))