Ex. No. 6 Implementation of Binary Search Tree
Ex. No. 6 Implementation of Binary Search Tree
AIM:
ALGORITHM:
Insertion:
1. If node to be deleted is leaf node then search the parent of the leaf node and make the link
of the leaf node as NULL.
2. If node to be deleted has only one child then search the parent of that node and assign the
link of the parent node to the child of the node to be deleted.
3. If the node to be deleted has two children then follow the following steps
- Copy the minimum value of its right subtree to deleted node position(del_node).
- Deallocte the memory of del_node.
PROGRAM:
#include<conio.h>
#include<stdio.h>
struct treenode;
typedef struct treenode *position;
typedef struct treenode *searchtree;
position find(int x,searchtree t);
position findmin(searchtree t);
position findmax(searchtree t);
searchtree insert(int x,searchtree t);
searchtree delete(int x,searchtree t);
void display(searchtree t);
struct treenode
{
int element;
struct treenode *left;
struct treenode *right;
};
position t,p;
void main()
{
int op,x;
clrscr();
t=NULL;
while(1)
{
printf("\nBINARY SEARCH TREE OPERATIONS");
printf("\n1.insert 2.delete 3.find 4.find min 5.find max 6.display 7.quit\nenter option:");
scanf("%d",&op);
switch(op)
{
case 1:
printf("\nINSERT OPERATION");
printf("\nenter the element:");
scanf("%d",&x);
t=insert(x,t);
break;
case 2:
printf("\nDELETE OPERATION");
printf("\nenter the element:");
scanf("%d",&x);
t=delete(x,t);
break;
case 3:
printf("\nFIND OPERATION");
printf("\nenter the element:");
scanf("%d",&x);
p=find(x,t);
if(p==NULL)
printf("\nelement not found");
else
printf("\nthe element is found at the position %d",p);
break;
case 4:
printf("\nFIND MINIMUM OPERATION");
p=findmin(t);
printf("\nthe minimum element %d is found at the position %d",p->element,p);
break;
case 5:
printf("\nFIND MAXIMUM OPERATION");
p=findmax(t);
printf("\nthe maximum element %d is found at the position %d",p->element,p);
break;
case 6:
printf("\nDISPLAY OPERATION");
display(t);
break;
case 7:
exit(1);
break;
default:
printf("\nINVALID");
break;
}
}
}
position findmin(searchtree t)
{
if(t!=NULL)
while(t->left!=NULL)
t=t->left;
return t;
}
position findmax(searchtree t)
{
if(t!=NULL)
while(t->right!=NULL)
t=t->right;
return t;
}
searchtree insert(int x,searchtree t)
{
if(t==NULL)
{
t=(searchtree)malloc(sizeof(struct treenode));
if(t==NULL)
printf("\nout of space");
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;
}
Thus the program for binary search tree is implemented and executed successfully.