Tuesday, 18 November 2014

Binary Search Tree insertion and deletion

#include<stdio.h>
struct node
{
int data;
struct node *l,*r;
};
typedef struct node node;
getnode()
{
return ((node *)malloc(sizeof(node)));
}
node *root;
insert(node *root,int val)
{
if(val<root->data&&root->l!=NULL)
{
insert(root->l,val);
}
if(val>=root->data&&root->r!=NULL)
{
insert(root->r,val);
}
if(val<root->data&&root->l==NULL)
{
    node *p=getnode();
    p->data=val;
p->l=NULL;
p->r=NULL;
root->l=p;
}
if(val>=root->data&&root->r==NULL)
{
   node *p=getnode();
    p->data=val;
p->l=NULL;
p->r=NULL;
root->r=p;

}
}
search(node *root,int val)
{
    if(root->data==val)return root;
    if(root->data>val&&root->l!=NULL){return search(root->l,val);}
    if(root->data<val&&root->r!=NULL){return search(root->r,val);}
    return NULL;
}
parent(node *root,int v)
{
    if(root->data==v){return root;}
    if(root->data>v){if(root->l->data==v){return root;}else return parent(root->l,v);}
    if(root->data<v){if(root->r->data==v){return root;}else return parent(root->r,v);}
}
inorder(node *root)
{
if(root!=NULL){

    inorder(root->l);
printf("%d\n",root->data);
inorder(root->r);

}
}
delete(node *cur,node *prev)
{
    if(cur->l==NULL&&cur->r==NULL)
    {
        if(prev->l==cur){prev->l=NULL;}
        if(prev->r==cur){prev->r=NULL;}
        free(cur);
        cur=NULL;
        return;
    }
    if(cur->l==NULL&&cur->r!=NULL)
    {
        if(prev->r==cur){prev->r=cur->r;}
        if(prev->l==cur){prev->l=cur->r;}
        free(cur);
        cur=NULL;
        return;
    }
    if(cur->l!=NULL&&cur->r==NULL)
    {
        if(prev->l==cur){prev->l=cur->l;}
        if(prev->r==cur){prev->r=cur->l;}
        free(cur);
        cur=NULL;
        return;
    }
    if(cur->l!=NULL&&cur->r!=NULL)
    {
        node *res=cur->l;
        while(res->r!=NULL)
        {

            if(res->r->r==NULL){break;}
            res=res->r;
        }

        node *previous;
        if(res->r!=NULL){previous=res;res=res->r;}
        if(res->r==NULL){previous=cur;}



        cur->data=res->data;

        if(previous->l==res){previous->l=NULL;}

        if(previous->r==res){previous->r=NULL;}

        free(res);
        res=NULL;
        return;
    }
}

main()
{
int a[]={50,40,42,43,41,30,60,70,65};
root=getnode();
node *p=root;
root->l=NULL;
root->r=NULL;
root->data=a[0];
int i;
for(i=1;i<9;i++)
{
insert(root,a[i]);
root=p;
}
inorder(root);
root=p;
int del;
printf("Enter the value to be deleted\n");
scanf("%d",&del);
node *de=search(root,del);
if(de==NULL){printf("\nValue does not exist");exit(0);}
root=p;
node *prev=parent(root,del);
root=p;
delete(de,prev);
inorder(p);
}

No comments:

Post a Comment