Wednesday, 16 May 2018

assignment

#include<iostream>
#include<cmath>
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,m=1;



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;
 for(int i=0;i<=a;i++)
{
  if(a==pow(2,i))
{
root=add(root,a);
m=0;
break;

}

}
if (m==0)
{
cout<<"Number is added"<<endl;
m=1;
}
else
    cout<<"Number is not added"<<endl;

break;
case 2:

  disply(root);

  cout<<endl;

break;

case 3:

 cout<<"Enter the number for delete"<<endl;

 cin>>a;
 for(int i=0;i<=a;i++)
{
  if(a==pow(2,i))
{
 root=deleteNode(root,a);
m=0;
break;}

}
if (m==0)
{
cout<<"Number is deleted"<<endl;
m=1;
}
else
    cout<<"Number is not deleted "<<endl;


 break;

}

}

}

No comments:

Post a Comment