Iterative program to count leaf nodes in a Binary Tree | Python3 program to count leaf nodes in a Binary Tree ; Helper function that allocates a new Node with the given data and None left and right pointers . ; Function to get the count of leaf Nodes in a binary tree ; If tree is empty ; Initialize empty queue . ; Do level order traversal starting from root Initialize count of leaves ; Driver Code ; 1 / \ 2 3 / \ 4 5 Let us create Binary Tree shown in above example ; get leaf count of the above created tree
from queue import Queue NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def getLeafCount ( node ) : NEW_LINE INDENT if ( not node ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT q = Queue ( ) NEW_LINE count = 0 NEW_LINE q . put ( node ) NEW_LINE while ( not q . empty ( ) ) : NEW_LINE INDENT temp = q . queue [ 0 ] NEW_LINE q . get ( ) NEW_LINE if ( temp . left != None ) : NEW_LINE INDENT q . put ( temp . left ) NEW_LINE DEDENT if ( temp . right != None ) : NEW_LINE INDENT q . put ( temp . right ) NEW_LINE DEDENT if ( temp . left == None and temp . right == None ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE print ( getLeafCount ( root ) ) NEW_LINE DEDENT