Earn without any Investment!

Monday, October 25, 2010

Binary tree Traversal

      #include<iostream.h>
      #include<conio.h>
      #include<stdio.h>
      #include<stdlib.h>
      struct node
      {
           int data;
           node *left;
           node *right;
      }*tree;

      //*tree=NULL;
      node *insert(node *tree,int ele);

      void preorder(node *tree);
      void inorder(node *tree);
      void postorder(node *tree);
      int count=1;

      void main()
      {
           clrscr();
           char ch;
           int ele;
           do
           {
            clrscr();
            cout<<"\n\t1----INSERT A NODE IN A BINARY TREE.";
            cout<<"\n\t2----PRE-ORDER TRAVERSAL.";
            cout<<"\n\t3----IN-ORDER TRAVERSAL.";
            cout<<"\n\t4----POST-ORDER TRAVERSAL.";
            cout<<"\n\t5----EXIT.";
            cout<<"\n\tENTER CHOICE::";
            ch=getch();
            switch(ch)
            {
             case '1':

             cout<<"\n\tENTER THE ELEMENT::";
             cin>>ele;
             tree=insert(tree,ele);
             break;

             case '2':
             cout<<"\n\t****PRE-ORDER TRAVERSAL OF A TREE****";
             preorder(tree);
             getch();
             break;

             case '3':
             cout<<"\n\t****IN-ORDER TRAVERSAL OF A TREE****";
             inorder(tree);
             getch();
             break;

             case '4':
             cout<<"\n\t****POST-ORDER TRAVERSAL OF A TREE****";
             postorder(tree);
             getch();
             break;

             case '5':
             exit(0);
            }
           }while(ch!='5');
      }

      node *insert(node *tree,int ele)
      {
           if(tree==NULL)
           {
            tree=new node;
            tree->left=tree->right=NULL;
            tree->data=ele;
            count++;
           }
           else
           if(count%2==0)
           tree->left=insert(tree->left,ele);
           else
           tree->right=insert(tree->right,ele);
           return(tree);
      }

      void
       preorder(node *tree)
      {
           if(tree!=NULL)
           {
            cout<<tree->data<<"\t";
            preorder(tree->left);
            preorder(tree->right);
                   }
      }

      void inorder(node *tree)
      {
           if(tree!=NULL)
           {
            inorder(tree->left);
            cout<<tree->data<<"\t";
            inorder(tree->right);
            }
      }

      void postorder(node *tree)
      {
           if(tree!=NULL)
           {
            postorder(tree->left);
            postorder(tree->right);
            cout<<tree->data<<"\t";
            }
      }

No comments:

Post a Comment