Iterative program to count leaf nodes in a Binary Tree | C ++ Program for above approach ; Node class ; Program to count leaves ; If the node itself is " null " return 0 , as there are no leaves ; It the node is a leaf then both right and left children will be " null " ; Now we count the leaves in the left and right subtrees and return the sum ; Class newNode of Node type ; Driver Code ; get leaf count of the above created tree
#include <iostream> NEW_LINE using namespace std ; struct node { int data ; struct node * left ; struct node * right ; } ; int countLeaves ( struct node * node ) { if ( node == NULL ) { return 0 ; } if ( node -> left == NULL && node -> right == NULL ) { return 1 ; } return countLeaves ( node -> left ) + countLeaves ( node -> right ) ; } struct node * newNode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } int main ( ) { struct node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; cout << countLeaves ( root ) << endl ; }