Thursday, 24 November 2016

Tree Traversing

//C++ Program TO Process Tree Traversing


#include<iostream.h>
#include<conio.h>
#define NULL 0
struct node
{
 struct node *left;
 int data;
 struct node *right;
};
class tree
{
 struct node *p,*t,*root;
 public:
            tree()
            {
             root=new node;
             root=NULL;
             }
             struct node *creation(struct node *p,int x);
             void inorder(struct node *p);
             void preorder(struct node *p);
             void postorder(struct node *p);
};
struct node *tree::creation(struct node *p,int x)
{
 if(p==NULL)
 {
  t=new node;
  t->data=x;
  t->left=NULL;
  t->right=NULL;
  p=t;
  }
 else if(x<p->data) p->left=creation(p->left,x);
  else p->right=creation(p->right,x);
 return p;
 }
 void tree::preorder(struct node *p)
 {
  if(p!=NULL)
  {
   cout<<"  "<<p->data;
   preorder(p->left);
   preorder(p->right);
   }
  }
 void tree::inorder(struct node *p)
 {
  if(p!=NULL)
  {
   inorder(p->left);
   cout<<"  "<<p->data;
   inorder(p->right);
   }
  }
 void tree::postorder(struct node *p)
 {
  if(p!=NULL)
  {
   postorder(p->left);
   postorder(p->right);
   cout<<"  "<<p->data;
   }
  }
void main()
{
 clrscr();
 tree t;
 int c,x;
 struct node *r;
 cout<<"\n\t\t TREE TRAVERSAL";
 cout<<"\n\t\t ~~~~~~~~~~~~~~";
 cout<<"\n";
 cout<<"\n";
 cout<<"\t * Enter The Root Value: " ;
 cin>>x;
 r=t.creation(NULL,x);
 do
 {
  cout<<"\n";
  cout<<"\t Enter The Number : ";
  cin>>x;
  t.creation(r,x);

  cout<<"\n";
  cout<<" Press 1 To Continue : ";
  cin>>c;
  }while(c==1);
 cout<<"\n";
 cout<<"\t\t Traversals \n";
 cout<<"\t\t ~~~~~~~~~~ \n";
 cout<<"\n";
 cout<<"\t Preorder : ";
 t.preorder(r);
 cout<<"\n";
 cout<<"\t Inorder  : ";
 t.inorder(r);
 cout<<"\n";
 cout<<"\t Postorder: ";
 t.postorder(r);
 getch();

 }

No comments:

Post a Comment