This python article is about counting leaf nodes in a binary tree. A tree is a type of data structure with a hierarchical structure. It contains parent nodes as well as child nodes. Binary Tree is a tree with following set of rules:
Each node can have either 0, 1 or 2 child nodes.
Each child node can have only 1 parent node.
Leaf nodes are nodes that do not have any child nodes. In our program we, first create a class 'Node' in it we create a constructor to create instance of class Node. After that we, create a function 'insert' to insert new nodes in our binary tree. When a node inserted is less than its parent node then it is placed as left child of the parent node and when the inserted node is greater than parent node it is placed as the right child of the parent node. For achieving this we compare the inserted node and its parent node in the 'insert' function itself. Then, we create a 'PrintTree' function to print the tree we'll create using the insert method. Out of the class Node, we create a function 'getLeafCount' to count the number of leaf nodes.
In our program, we then create nodes using the insert method and by passing values of the nodes to be inserted. After that we call the getLeafCount function to count the leaf nodes in our tree.
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
if data < self.data:
if self.left is None:
self.left = Node(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
self.data = data
if node is None:
if(node.left is None and node.right is None):
return (getLeafCount(node.left) + getLeafCount(node.right))
root = Node(14)
print ("Leaf count of the tree is ",getLeafCount(root))