Tuesday, 13 December 2011

BST Creation, Insertion and Display


#include<stdio.h>
#include<stdlib.h>
#include<conio.h>


struct searchtree
{
   int element;
   struct searchtree *left,*right;
}*root;
typedef struct searchtree *node;
typedef int ElementType;


node insert(ElementType, node);
void makeempty();
void display(node, int);
void makeempty()
{
root = NULL;
}


void main()
{
int ch;
ElementType a;
makeempty();
while(1)
{


printf("\n1. Insert\n2. Display\n3. Exit\n");
                printf("\nEnter Your Choice : ");
scanf("%d",&ch);
switch(ch)
{


case 1:
printf("Enter an element : ");
scanf("%d", &a);
root = insert(a, root);
break;
  case 2: if(root==NULL)
                 printf("\nEmpty tree");
                   else display(root, 1);
                   break;
       case 3: exit(0);
           default:printf("Invalid Choice");
      }
   }
}
node insert(ElementType x, node t)
{
if( t == NULL)
   {
t = (node)malloc(sizeof(node));
t->element = x;
t->left = t->right = NULL;


}else
{
    if(x < t->element) t->left = insert(x, t->left);
        else if(x > t->element) t->right = insert(x, t->right);
   }
   return t;
}


void display(node t,int level)
{
int i;
if(t)
{


display(t->right, level+1);
printf("\n");
for(i=0;i<level;i++)


printf(" ");
printf("%d", t->element);
display(t->left, level+1);


   }


}

Output look like this :


No comments:

Post a Comment