Tuesday 24 January 2012

Tree Sort(Using tree traversal)


*Author-Neelkant.S.Patil,GMIT,Davanagere*/


#include <stdlib.h>
typedef struct tnode
 {
  int data;
  struct tnode *right,*left;
 }TNODE;


TNODE *CreateBST(TNODE *, int);
void Inorder(TNODE *);




void main()
  {
   TNODE *root=NULL; /* Main Program */
   int opn,elem,n,i;
   do
    {
     clrscr();
     printf("\n ### Binary Search Tree Operations ### \n\n");
     printf("\n Press 1-Creation of BST");
     printf("\n       2-SORT(Traverse in Inorder)");
     printf("\n       3-Exit\n");
     printf("\n       Your option ? ");
     scanf("%d",&opn);
     switch(opn)
      {
       case 1: root=NULL;
      printf("\n\nBST for How Many Nodes ?");
      scanf("%d",&n);
      for(i=1;i<=n;i++)
      {
      printf("\nRead the Data for Node %d ?",i);
      scanf("%d",&elem);
      root=CreateBST(root,elem);
      }
      printf("\nBST with %d nodes is ready to Use!!\n",n);
      break;
       case 2: printf("\n AFTER SORTING\n");
      Inorder(root); break;


       default: exit(0);
break;
      }
      printf("\n\n\n\n  Press a Key to Continue . . . ");
      getch();
      }while(opn != 5);
  }




 TNODE *CreateBST(TNODE *root, int elem)
   {
    if(root == NULL)
     {
      root=(TNODE *)malloc(sizeof(TNODE));
      root->left= root->right = NULL;
      root->data=elem;
      return root;
     }
     else
     {
      if( elem < root->data )
 root->left=CreateBST(root->left,elem);
      else
      if( elem > root->data )
 root->right=CreateBST(root->right,elem);
      else
printf(" Duplicate Element !! Not Allowed !!!");


     return(root);
     }
  }
void Inorder(TNODE *root)
  {
   if( root != NULL)
      {
      Inorder(root->left);
      printf(" %d ",root->data);
      Inorder(root->right);
      }
  }











No comments:

Post a Comment