C program to count the leaves of the binary tree.

Write a C program to count the leaves of the binary tree.
Binary tree is the ordered directed tree data structure, in which each node has at most two nodes.
A node is called as a leaf node,  if it does not contains any child elements. In this program, We used the structures to create the binary tree.

/***********************************************************
* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
*
* Happy Coding
***********************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

struct node
{
int data;
struct node* leftnode;
struct node* rightnode;
};

//get the leaves count
unsigned int getLeafCount(struct node* node)
{
if(node == NULL)
return 0;
if(node->leftnode == NULL && node->rightnode==NULL)
return 1;
else
return getLeafCount(node->leftnode)+
getLeafCount(node->rightnode);
}

struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->leftnode = NULL;
node->rightnode = NULL;

return(node);
}

int main()
{

clrcsr();
struct node *root = newNode(1);
root->leftnode = newNode(2);
root->rightnode = newNode(3);
root->leftnode->leftnode = newNode(4);
root->leftnode->rightnode = newNode(5);

printf("nnLeaf count of the binary tree is %d", getLeafCount(root));

getch();
return 0;
}

Data Structures
Learn C Programming

You can easily select the code by double clicking on the code area above.