Friday, August 31, 2012

C Program to Count number of nodes in Binary Tree

#include<iostream.h>
#include<alloc.h>
#include<conio.h>
struct tree
{
       int item;
       struct tree *right,*left;
};
void create(struct tree *p)
{
     int choice;
     cout<<"\nEnter value";
     cin>>p->item;
     cout<<"Do you Want to Enter left Child of "<<p->item<<" .1.YES/2.NO";
     cin>>choice;
     if(choice==1)
     {
          p->left=(tree*)malloc(sizeof(tree));
          create(p->left);
     }
     else
     {
          p->left=NULL;
     }
     cout<<"Do you Want to Enter Right Child of  "<<p->item<<" .1.YES/2.NO";
     cin>>choice;
     if(choice==1)
     {
          p->right=(tree*)malloc(sizeof(tree));
          create(p->right);
     }
     else
     {
          p->right=NULL;
     }
}
static int i=0;
void count(struct tree *p)
{
     if(p==NULL)return;
     i++;
     count(p->left);
     count(p->right);
}
int main()
{
     clrscr();
     struct tree *a;
     a=(tree*)malloc(sizeof(tree));
     cout<<"Enter Tree\n";
     create(a);
     count(a);
     cout<<"\nTotal Nodes="<<i;
     getch();
     return 0;
}

No comments:

Post a Comment