Iterative program to count leaf nodes in a Binary Tree | Node class ; Program to count leaves ; If the node itself is " None " return 0 , as there are no leaves ; It the node is a leaf then both right and left children will be " None " ; Now we count the leaves in the left and right subtrees and return the sum ; Driver Code ; get leaf count of the above created tree
class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def countLeaves ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( node . left == None and node . right == None ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return countLeaves ( node . left ) + countLeaves ( node . right ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE print ( countLeaves ( root ) ) NEW_LINE DEDENT