Monday, 12 February 2018

add show add delete node from tree

#include<iostream>
using namespace std;
struct tree
{
 int num;
 tree* left,*right;

}*root;
tree * create(int n)
{
 tree *t= new tree;
 t->num=n;
 t->left=t->right=NULL;
 return t;

}
tree * add(tree * r,int nu)
{
      if(r==NULL)
      {
        r= create(nu);
     
   }
   else if(nu<=r->num)
   {
     r->left= add(r->left,nu);
   }
   else
   r->right=add(r->right,nu);
   return r;
}
void disply(tree * t)
{
 if(t==NULL)
 {
  return;
 }
 else
 {
    cout<<t->num<<"   ";
    disply(t->left);
 
    disply(t->right);
 }
 }
tree * deletes(tree * t)
{
while(t->left!=NULL)
{
  t=t->left;
}return t;
}
tree * deleteNode(tree * r,int d)
{
 if(r==NULL)
 {
  return r;
 }
 else if(d<r->num)
 {
  r->left=deleteNode(r->left,d);
 
 }
 else if(d>r->num)
 {
  r->right=deleteNode(r->right,d);
 
 }
 else {
  if(r->left==NULL&&r->right==NULL)
  {
  delete r;
  r=NULL;
}
else if(r->right==NULL)
{
tree * temp;
temp=r;
r=r->left;
delete temp;
}
  else if(r->left==NULL)
{
tree * temp;
temp=r;
r=r->right;
delete temp;
}
else
{
  tree *temp=deletes(r->right);
  r->num=temp->num;
 
  r->right=deleteNode(temp,temp->num);
}

 }
 return r;
}

int main()
{
root==NULL;
int n,a;
while(1){

cout<<"Enter 1 for add Enter 2 for display Enter 3  for delete node"<<endl;
cin>>n;
switch(n)
{
case 1:
 cout<<"Enter the number for add"<<endl;
 cin>>a;
root=add(root,a);
break;
case 2:
  disply(root);
  cout<<endl;
break;
case 3:
cout<<"Enter the number for delete"<<endl;
 cin>>a;
root=deleteNode(root,a);
break;
}


}
}

1 comment: