text: Program to count leaf nodes in a binary tree | C implementation to find leaf count of a given Binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; Function to get the count of leaf nodes in a binary tree ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver program to test above functions ; create a tree ; get leaf count of the above created tree
code: #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int data ; struct node * left ; struct node * right ; } ; unsigned int getLeafCount ( struct node * node ) { if ( node == NULL ) return 0 ; if ( node -> left == NULL && node -> right == NULL ) return 1 ; else return getLeafCount ( node -> left ) + getLeafCount ( 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 ) ; printf ( " Leaf ▁ count ▁ of ▁ the ▁ tree ▁ is ▁ % d " , getLeafCount ( root ) ) ; getchar ( ) ; return 0 ; }