CREATE A PROGRAM TO INSERT, DELETE, SEARCH,DISPLAY DATA OF TREE DATA STRUCTURE USING C++.




#include<iostream.h>
#include<conio.h>
#include<alloc.h>
#include<stdlib.h>
#define NULL0
struct node
{
int data;
struct node *leftptr;
struct node *rightptr;
};
typedef struct node tree;
tree* insertion(int item, tree* root)
{
if(root == NULL)
{
root=(tree *)malloc(sizeof(tree));
root->data=item;
root->leftptr=NULL;
root->rightptr=NULL;
return(root);
}
if(root->data >= item)
root->leftptr=insertion(item,root->leftptr);
else
root->rightptr=insertion(item,root->rightptr);

return(root);
}
tree* deletion(tree* root,int data)
{
tree* tmp;
if(root==NULL)
{
cout<<"\nElement Not Found";
cout<<"\n";
return(root);
}
else
if(root->data>data)
root->leftptr=deletion(root->rightptr,data);
else if(root->data<data)
root->rightptr=deletion(root->rightptr,data);
else
{
tmp=root;
       if(tmp->leftptr==NULL)
{
root=tmp->rightptr;
cout<<"\nDeleted Element: "<<data;
delete(tmp);
}
else if(tmp->rightptr==NULL)
{
root=tmp->leftptr;
cout<<"\nDeleted Element: "<<data;
delete(tmp);
}
else
{
cout<<"\nOperation cannot be Performed";
}
}
return(root);
}

int search(tree* root,int data)
{
int flag=0;
while(root!=NULL)
{

           if(root->data==data)
{
flag=1;
return(flag);
}
else
if(data<root->data)
{
root=root->leftptr;
}
else
{
root=root->rightptr;
}
}
return 0;
}

void display(tree* root)
{
if(root!=NULL)
{
display(root->rightptr);
cout<<"\n"<<root->data<<endl;
display(root->leftptr);
}
}

void main()
{
int n,x;
char ch='y';
tree * root=NULL;
clrscr();
while(ch=='y'||ch=='Y')
{
cout<<"\n1.Add new node into the tree";
cout<<"\n2.Delete node from the tree";
cout<<"\n3.Searching a node into the tree";
cout<<"\n4.Display node of the tree";
cout<<"\n5.Exit";
cout<<"\n\nEnter your Choice==>";
cin>>n;
switch(n)

          {
case 1:
cout<<"\nEnter value to insert in a tree==>";
cin>>x;
root=insertion(x,root);
break;

case 2:
int a;
cout<<"\nEnter The Element To Delete: ";
cin>>a;
root=deletion(root,a);
break;

case 3:
int flag,x;
cout<<"\nSearch the Element: ";
cin>>x;
flag=search(root,x);
if(flag)
cout<<"\nElement Found: "<<x;
else
cout<<"\nElement not Found"<<endl;
break;

case 4:
display(root);
break;

case 5:
exit(0);
default:
cout<<"\nWrong choice input again";
cout<<"\n";
}
}
getch();
}

Post a Comment

0 Comments