C program to count the number of nodes in the binary search tree

				
					#include < stdio.h >
#include < conio.h >
#include < alloc.h >
#define new_node (struct node*)malloc(sizeof (struct node))

struct node
{
int data;
struct node *lchild;
struct node *rchild;
};
struct node *create_bin_rec();
void print_bin_pre_rec(struct node *t);
void cnt_nodes(struct node *t, int *l, int *nl);
void main()
{
struct node *root;
int leaf,nonleaf;
clrscr();
printf("\nCreate a binary tree \n");
root = create_bin_rec();
printf("\n Binary tree is ");
print_bin_pre_rec(root);
leaf = nonleaf = 0;
cnt_nodes(root,&leaf,&nonleaf);
printf("\n Total no. of leaf nodes are : %d ",leaf);
printf("\n Total no. of nonleaf nodes are : %d ",nonleaf);
printf("\n Total no. of nodes are : %d ", (leaf+nonleaf));
} // main

struct node *create_bin_rec()
{
int data;
struct node *t;
printf("\nData ( -1 to exit ) : ");
scanf("%d",&data);
if( data == -1)
return(NULL);
else
{
t = new_node;
t->data = data;
t->lchild =create_bin_rec();
t->rchild =create_bin_rec();
return(t);
} //else
} // create

void print_bin_pre_rec(struct node *t)
{
if( t != NULL)
{
printf("%4d",t->data);

print_bin_pre_rec(t->lchild);
print_bin_pre_rec(t->rchild);
} // if
} // print bin pre rec
void cnt_nodes(struct node *t, int *l, int *nl)
{
if( t != NULL)
{
if( t->lchild == NULL && t->rchild == NULL)
(*l)++;
else
(*nl)++;
cnt_nodes(t->lchild,l,nl);
cnt_nodes(t->rchild,l,nl);
} // if
} // cnt nodes


				
			

INPUT OUTPUT

Create binary tree Data (-1 to exit) 10
Data (-1 to exit) 20
Data (-1 to exit)  -1
Binary tree is 10 20
Total no. of leaf nodes are 1
Total no. of non leaf nodes are 1
Total no. of nodes are 2

Leave a Reply