Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 4

#include<stdio.

h>
#include<conio.h>
struct node
{
int info;
struct node *l,*r;
};
typedef struct node node1;
void initbst(node1 **root)
{
*root = NULL;
}
void insertbst(node1 **root,int x)
{
node1 *p,*q,*back;
p = (node1*)(malloc(sizeof(node1)));
p->info = x;
p->l = NULL;
p->r = NULL;
if(*root == NULL)
{
*root = p;
}
else
{
q = *root;
back = *root;
while(q!=NULL)
{
back = q;
if(x<=q->info)
q = q->l;
else q=q->r;
}
if(x<=back->info)
back->l = p;
else back->r = p;
}
}
void inorder(node1*root)
{
if(root!=NULL)
{
inorder(root->l);
printf("%d\t",root->info);
inorder(root->r);
}
}
void preorder(node1*root)
{
if(root!=NULL)
{
printf("%d\t",root->info);
preorder(root->l);
preorder(root->r);
}
}
void postorder(node1*root)
{
if(root!=NULL)
{
inorder(root->l);
inorder(root->r);
printf("%d\t",root->info);
}
}
int searchbst(node1*root,int x)
{
node1 *p;
p = root;
while(p!=NULL && p->info!=x)
{
if(x<=p->info)
p = p->l;
else
p = p->r;
}
if(p == NULL) return 0;
else return 1;
}

void deletebst(node1**root, int x)


{
node1 *p,*q,*back;
back = *root;
p = *root;
while(p!=NULL && p->info!=x)
{
back = p;
if(x<=p->info)
p = p->l;
else p = p->r;
}
if(p == NULL) printf("Value is not present\n");
else
{
if(p->l==NULL && p->r==NULL)
{
if(back->l==p)
back->l=NULL;
else back->r=NULL;
free(p);
}
else if(p->l==NULL || p->r==NULL)
{
if(p->l==NULL)
{
if(back->l==p)
back->l=p->r;
else back->r=p->r;
}
else
{
if(back->l==p)
back->l=p->l;
else back->r=p->l;
}
free(p);
}
else
{
q = p;
p = p->l;
back = p;
while(p->r!=NULL)
{
back = p;
p = p->r;
}
if(back == p)
{
q->info = p->info;
q->l = p->l;
free(p);
}
else
{
q->info = p->info;
back->r = p->l;
free(p);
}
}
}
}

int main()
{
node1 *root;
int x,ch,w;
w = 1;
initbst(&root);
while(w)
{
printf("\nEnter choice:\n1.Insert\n2. Inorder traversal\n3. Preorder
traversal\n4. Postorder traversal\n5. Delete\n6. Search\n7. Exit\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter the element to be inserted:\n");
scanf("%d",&x);
insertbst(&root,x);
break;
case 2:
inorder(root);
break;
case 3:
preorder(root);
break;
case 4:
postorder(root);
break;
case 5:
printf("Enter the element to be deleted:\n");
scanf("%d",&x);
deletebst(&root,x);
break;
case 6:
printf("Enter the element to be searched:\n");
scanf("%d",&x);
if(searchbst(root,x)==1) printf("Element found\n");
else
printf("Element not present\n");
break;
case 7:
w = 0;
break;
default :
printf("Invalid choice\n");
}
}
}

You might also like