Saturday, September 3, 2011

Binary Search Tree



/* A menu driven program for binary search tree creation and inorder,
   preorder,postorder recursive traversals of all nodes.Modify the program
   for performing following operations:
   (a) Search a value (b) Insertion of a value
*/

#include<stdio.h>
#include<stdlib.h>
typedef struct BSTnode
{
int data;
struct BSTnode *left,*right;
}BSTnode;

BSTnode *insert(BSTnode *,int);
BSTnode *create();
void inorder(BSTnode *T);
BSTnode * tcopy(BSTnode *T);
int tmirror(BSTnode *T1,BSTnode *T2);
int tleafcount(BSTnode *T);

int main()
{
BSTnode *root1=NULL, *root2=NULL,*root3;
int x,op;
do
 { printf("\n\n1)Create\n2)Copy of 1st tree\n3)t2 is mirror of t1 ? ");
   printf("\n4)Count leaf nodes \n5)Quit");
   printf("\nEnter Your Choice :");
   scanf("%d",&op);
    switch(op)
     {
case 1: printf("\nCreate 1st tree");
root1=create();
printf("\nCreate 2nd tree");
root2=create();
break;
case 2: root3=tcopy(root1);
printf("\nInorder traversal on copied tree : ");
inorder(root3);
break;
case 3: if(tmirror(root1,root2))
    printf("\nt1 is mirror of t2");
else
    printf("\nt1 is not mirror of t2");
break;
case 4:printf("\nLeaf node in t1=%d",tleafcount(root1));
      printf("\nLeaf node in t2=%d",tleafcount(root2));
      break;
    }
}while(op!=5);
}


void inorder(BSTnode *T)
{
if(T!=NULL)
{
inorder(T->left);
printf("%d\t",T->data);
inorder(T->right);
}
}

BSTnode *insert(BSTnode *T,int x)
{
BSTnode *r;
// acquire memory for the new node
if(T==NULL)
 {
r=(BSTnode*)malloc(sizeof(BSTnode));
r->data=x;
r->left=NULL;
r->right=NULL;
return(r);
 }


if(x>T->data)
 {
T->right=insert(T->right,x);
return(T);
 }
else
if(x<T->data)
 {
T->left=insert(T->left,x);
return(T);
 }
else //duplicate data
return(T);
 }

BSTnode *create()
{
int n,x,i;
BSTnode *root;
root=NULL;
printf("\nEnter no. of nodes :");
scanf("%d",&n);
printf("\nEnter tree values :");
for(i=0;i<n;i++)
{
scanf("%d",&x);
root=insert(root,x);
}
return(root);
}

BSTnode *tcopy(BSTnode *T)
   {
      BSTnode *p;
      if(T==NULL)
return(NULL);
      p=(BSTnode*)malloc(sizeof(BSTnode));
      p->data=T->data;
      p->left=tcopy(T->left);
      p->right=tcopy(T->right);
      return(p);
   }
int tmirror(BSTnode *T1,BSTnode *T2)
   {
      if(T1==NULL && T2==NULL)
return(1);
      if(T1==NULL || T2==NULL)
return(0);
      if(T1->data==T2->data && tmirror(T1->left,T2->right) &&
      tmirror(T1->right,T2->left))
return(1);
      return(0);
   }
int tleafcount(BSTnode *T)
    {
       if(T==NULL)
return(0);
       if(T->left==NULL && T->right==NULL)
return(1);
       return(tleafcount(T->left)+tleafcount(T->right));
    }


No comments:

Post a Comment