Monday, 12 February 2018

how to create tree and display all its elements


#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);
 }
 }

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

cout<<"Enter 1 for add Enter 2 for display"<<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;
}


}
}

No comments:

Post a Comment