Saturday, September 3, 2011

Various operations on binary search tree


// program showing various operations on binary search tree
#include<stdio.h>
#include<stdlib.h>
typedef struct BSTnode
{
int data;
struct BSTnode *left,*right;
}BSTnode;

typedef struct stack
  { BSTnode *data[20];
    int top;
  }stack;

void init(stack *s)
 { s->top=-1;
 }

BSTnode * pop(stack *s)
 { BSTnode *p;
   p=s->data[s->top];
   s->top=s->top-1;
   return(p);
 }

void  push(stack *s, BSTnode *p)
  { s->top=s->top+1;
    s->data[s->top]=p;
  }

int empty(stack *s)
 { if(s->top==-1)
     return(1);
   return(0);
 }
int full(stack *s)
  {  if(s->top==19)
return(1);
     return(0);
  }


BSTnode *insert(BSTnode *,int);
BSTnode *create();
void non_rec_preorder(BSTnode *T);
void non_rec_postorder(BSTnode *T);
void non_rec_inorder(BSTnode *T);

int main()
{
BSTnode *root=NULL,*p;
int x,op;
do
 { printf("\n\n1)Create\n2)Preorder(non-recursive)");
   printf("\n3)Inorder(non-recursive)\n4)Posorder(non-Recursive)");
   printf("\n5)Quit");
   printf("\nEnter Your Choice :");
   scanf("%d",&op);
    switch(op)
     {
case 1: root=create();break;
case 2: non_rec_preorder(root);break;
case 3: non_rec_inorder(root);break;
case 4: non_rec_postorder(root);break;
    }
}while(op!=5);
}


void non_rec_preorder(BSTnode *T)
 {
stack s;
init(&s);
printf("\n");
if(T==NULL)
return;
while(T!=NULL)
 {
printf("%d   ",T->data);
push(&s,T);
T=T->left;
 }
      while(!empty(&s))
{
T=pop(&s);
T=T->right;
while(T!=NULL)
 {
printf("%d   ",T->data);
push(&s,T);
T=T->left;
 }
}

 }

 void non_rec_postorder(BSTnode *T)
  {
stack s,s1;
BSTnode *flag;
init(&s);init(&s1);
printf("\n");
if(T==NULL)
   return;
while(T!=NULL)
  {
push(&s,T);push(&s1,NULL);
T=T->left;
  }
while(!empty(&s))
  {
T=pop(&s);flag=pop(&s1);
if(flag!=NULL)
printf("%d   ",T->data);
else
 {
push(&s,T);push(&s1,(BSTnode*)1);
T=T->right;
while(T!=NULL)
  {
push(&s,T);push(&s1,NULL);
T=T->left;
  }
}
  }
  }




void non_rec_inorder(BSTnode *T)
 {   stack s;
     init(&s);
     printf("\n");
     if(T==NULL)
      return;
      while(T!=NULL)
       { push(&s,T);
T=T->left;
       }
      while(!empty(&s))
       { T=pop(&s);
printf("%d   ",T->data);
T=T->right;
while(T!=NULL)
 { push(&s,T);
   T=T->left;
 }
       }
 }

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);
}

No comments:

Post a Comment