Binary Search Tree Program


The search opertions is performed in the binary tree  to search any  element in the tree, basic operations performed in the binary tree are :-

  • Preorder
  • Inorder
  • Postorder



Source Code:-

// header file
#include<conio.h>
#include<stdio.h>
//structure creation
// type casting for struct node
typedef struct node
{
int data ;
struct node*r;
struct node*l;
}tree;
//// PROTOTYPE

tree*insert(tree*, int);
void preorder(tree*);
void postorder(tree*);
void inorder(tree*);
void *search(tree*,int);

tree* t=NULL;
void main()
{
int option ,val,s;
clrscr();

do{
printf("\n main menu\n");
printf("\n1:INSERT");
printf("\n2:PREORDER");
printf("\n3:POSTORDER");
printf("\n4:INORDER");
printf("\n5:SEARCH");
printf("\n0:exit");
printf("\nenter your option:");
scanf("%d",&option);
// switch case implementation
switch(option)
{
case 1: printf("\n enter value to insert in tree\n");
scanf("%d",&val);
t=insert(t,val);
printf("\nINSERTION IS SUCCESS!!\n");
break;
case 2: printf("\n the element of tree in preorder\n\t");
preorder(t);
break;

case 3: printf("\n the element of tree in postorder\n\t");
postorder(t);
break;
case 4: printf("\n the element of tree in inorder\n\t");
inorder(t);
break;
case 5: printf("\n the element to be search");
printf("\n enter number to search:-");
scanf("%d",&s);
search(t,s);
break;
case 0: exit(0);
default :
printf("not a correct option") ;
}
}
while(option!=0);
getch();
}

// definition of the function
//insert value nodes at the point to be inserted
tree *insert(tree*t, int val)
{
tree *ptr,*nptr,*pptr ;
ptr=(tree*)malloc(sizeof(tree)) ;
ptr->data=val;
ptr->r=NULL;
ptr->l=NULL;
if(t==NULL)
{
t=ptr;
t->r=NULL;
t->l=NULL;
}
else
{
pptr=NULL;
nptr=t;
while (nptr!=NULL)
{
pptr=nptr;
if(val<nptr->data)
nptr=nptr->l;
else
nptr=nptr->r;
}
if(val<pptr->data)
pptr->l=ptr;
else
pptr->r=ptr;
}
return(t);
}
// definition
// root->left ->right
void preorder(tree*t)
{
if(t!=NULL)
{
printf("%d",t->data);
preorder(t->l);
preorder(t->r);
}
}

// definition of the function
void postorder(tree*t)
{
if(t!=NULL)
{
postorder(t->l);
postorder(t->r);
printf("%d\t",t->data);
}
}

void inorder(tree*t)
{
if(t!=NULL)
{
printf("%d\t",t->data);
inorder(t->l);
inorder(t->r);
}
}

void *search(tree *t,int val)
{
tree *ptr,*nptr,*pptr;
if(t==NULL)
{
printf("empty");
getch();
exit(0);
}
else
if(t->data==val)
{
printf("data found on root");
getch();
exit(0);
}
pptr=NULL;
nptr=t;
while(nptr!=NULL)
{
pptr=nptr;
if(val<nptr->data)
{
nptr=nptr->l;
printf("\n data found at left");
getch();
exit(0);
}
else
{
nptr=nptr->r;
printf("\n data found at right ");
getch();
exit(0);
}
}
     }

 


Post a Comment

Previous Post Next Post