class Node:
"""
prototype for node
"""
def __init__(self, data):
self.data = data
self.left = self.right = None
# Function to get the count of leaf
# Nodes in a binary tree
def getLeafCount(node):
"""
input: A node
return: count of leaf nodes
"""
# If tree is empty
if (not node):
return 0
# Initialize empty list.
l = []
# Initialize count of leaves
count = 0
# apppend root node in list
l.append(node)
# Do level order traversal
# starting from root
while (len(l) > 0):
"""
loop is continue as long as list l contain the elements
"""
# create temporary variable that contain the current node
temp = l[0]
# remove current node from list after creating reference temp
l.remove(l[0])
if (temp.left != None): # if left child is not None append it to list
l.append(temp.left)
if (temp.right != None): # if right child is not None append it to list
l.append(temp.right)
# if both child is None, means it is leaf node increse the count
if (temp.left == None and temp.right == None):
count += 1
return count
def main():
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print("count of leaf node is",getLeafCount(root))
if __name__ == '__main__':
main()
<!--count of leaf node is 3-->