Binary Search Tree Using C

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

#include<stdio.

h>

#include<stdlib.h>

#include<conio.h>

typedef struct node

int data;

struct node *left,*right;

}NODE;

NODE *root=NULL; int c1=0;

void insertion()

NODE *current ,*follow ,*start;

start=(NODE*)malloc(sizeof(NODE));

printf("Enter the data: ");

scanf("%d",&start->data);

start->left=start->right=NULL;

if(root==NULL)

root=start;

else

current=root;

follow=NULL;

while(current!=NULL)

follow =current;
if( start->data < current->data)

current=current->left;

else

current=current->right;

if(start->data<follow->data)

follow->left=start;

else

follow->right=start;

void deletion()

NODE *p=root,*temp,*follow,*s,*q=NULL;

int value;

printf("Enter element you want to delete: ");

scanf("%d",&value);

while(p!=NULL && p->data!=value)

q=p;

if(value<p->data)

p=p->left;

else

p=p->right;}

if(p==NULL)
printf("Node does not exist");

if(p->left==NULL)

temp=p->right;

else if(p->right==NULL)

temp=p->left;

else

follow=p;

temp=p->right;

s=temp->left;

while(s!=NULL)

follow=temp;

temp=s;

s=temp->left;

if(follow!=p)

follow->left=temp->right;

temp->right=p->right;

temp->left=p->left; }

if(q==NULL)

root=temp;

else if(p==(q->left))
(q->left)=temp;

else

(q->right)=temp;

void inorder(NODE *p1)

if(p1!=NULL)

inorder(p1->left);

printf("%d\t",p1->data);

inorder(p1->right);

void main()

int choice;

clrscr();

printf("1.INSERT\n2.DELETE\n3.INORDER TRAVERSAL\n4.EXIT");

do

printf("\nEnter your choice: ");

scanf("%d",&choice);

switch(choice)

{
case 1:insertion();break;

case 2:deletion();break;

case 3:inorder(root);break;

case 4:printf("Program exited");break;

default:printf("Invalid choice");}

}while(choice!=4);

getch();

You might also like