You are on page 1of 4

#include <stdio.

h>
#include<stdlib.h>

struct node
{
struct node *llink;
int data;
struct node *rlink;
};

struct node *root = NULL;

void insert()
{
struct node *temp, *cur, *prev;

temp = (struct node*)malloc(sizeof(struct node));


printf("\nEnter Value : ");
scanf("%d",&temp->data);
temp->llink = NULL;
temp->rlink = NULL;

if(root == NULL)
root = temp;

else
{
cur = root;
prev = NULL;

while(cur!=NULL)
{
prev = cur;
if(temp->data < cur->data)
cur = cur->llink;
else if(temp->data > cur->data)
cur = cur->rlink;
else
{
printf("\n\tDuplicate not allowed");
return;
}
}

if(temp->data < prev->data)


prev->llink = temp;
else
prev->rlink = temp;
}
}
void delete()
{
int ele,flag=0;
struct node *temp, *cur, *prev, *suc, *q;

if(root==NULL)
{
printf("\n\tTree is Empty");
return;
}

printf("\nEnter Value to be Deleted: ");


scanf("%d",&ele);

cur = root;
prev = NULL;

while(cur!=NULL)
{

if(cur->data == ele)
{
flag = 1;
break;
}
else if(ele < cur->data)
{
prev = cur;
cur = cur->llink;
}
else
{
prev = cur;
cur = cur->rlink;
}

if(flag==0)
{
printf("\n\tElement not found");
}
else
{
if (cur->llink == NULL)
q = cur->rlink;
else if (cur->rlink == NULL)
q = cur->llink;
else
{
suc = cur->rlink;

while(suc->llink!=NULL)
{
suc = suc->llink;
}

suc->llink = cur->llink;
q = cur->rlink;
}

if(cur == root)
{
free(root);
root = q;
return;
}

if(cur == prev->llink)
{
prev->llink = q;
free(cur);
}
else
{
prev->rlink = q;
free(cur);
}
}

void display(struct node *r)


{
if(r!=NULL)
{
display(r->llink);
printf("%d\t",r->data);
display(r->rlink);
}
}

int main()
{
int ch;
while(1)
{
printf("\nEnter Choice\n1-Insertion\n2-Deletion\n3-Display\
n4-Exit\n");
printf("\nAnswer :");
scanf("%d",&ch);
switch(ch)
{
case 1 : insert();
break;
case 2 : delete();
break;
case 3 : if(root == NULL)
printf("\n\tTree is Empty");

else
{
printf("\nElements of the Tree(In-Order) :");
display(root);
}
break;
case 4 : exit(0);

default : printf("\n\tInvalid Choice");


}
}
return 0;
s}

You might also like