Friday, August 31, 2012

C Program to Compare two Trees

/* Compare two trees Considering Branches As Well AS Values*/
#include<iostream.h>
#include<conio.h>
#include<alloc.h>
struct tree
{
       int item;
       struct tree *right,*left;
};
void create(struct tree *p)
{
     int choice;
     cout<<"\nEnter value";
     cin>>p->item;
     cout<<"\nDo 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;
     }
}
void print_inorder(struct tree *p)
{
     if(p==NULL)return;
     print_inorder(p->left);
     cout<<endl<<p->item;
     print_inorder(p->right);
}
int compare(tree *p,tree *q)
{
   if(p==NULL&&q==NULL)
   return 1;
   else if(p==NULL||q==NULL)
   return 0;
   else if(p->item==q->item)
   {
    int s1=compare(p->left,q->left);
    int s2=compare(p->right,q->right);
    return s1*s2;
   }
   else
   return 0;
}
void main()
{
     clrscr();
     struct tree *a;
     cout<<"\nProgram To Compare Two Trees\n";
     cout<<"Enter First Tree\n";
     a=(tree*)malloc(sizeof(tree));
     create(a);
     struct tree *b;
     cout<<"\nEnter Second Tree\n";
     b=(tree*)malloc(sizeof(tree));
     create(b);
     if(compare(a,b)==1)
     cout<<"Both Trees Have Similar Branches With Values";
     else
     cout<<"Both Trees doesn't have Similar Branches With Values";
     getch();
}

No comments:

Post a Comment