Wednesday, August 14, 2013

Binary Tree

//C programming for designing Binary Tree
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<stdlib.h>
struct bst
    {
   int data ;
   struct bst *leftlink;
   struct bst *rightlink;
   };
   void insert(struct bst **root ,int num)
   {
   struct bst *temp;
   temp=(struct bst *)malloc(sizeof(struct bst));
   temp->data=num;
   temp->leftlink=NULL;
   temp->rightlink=NULL;
   if(*root==NULL)
       {
      *root=temp;
      }
   else if(num<(*root)->data)
       {
      insert(&((*root)->leftlink),num);
      }
   else if(num>(*root)->data)
       {
      insert(&((*root)->rightlink),num);
      }
   else
       printf("duplicate entry.\n");
      }
    void inorder(struct bst *root)
       {
      if(root==NULL)
          return;
      else
          {
          inorder(root->leftlink);
          printf("%d\t",root->data);
          inorder(root->rightlink);
          }
      }
      void preorder(struct bst *root)

          {
         if(root==NULL)
            return;
      else
          {
         printf("%d\t",root->data);
         preorder(root->leftlink);
         preorder(root->rightlink);
         }
         }
     void postorder(struct bst *root)
             {
          if(root==NULL)
            return;
          else
              {
            postorder(root->leftlink);
             postorder(root->rightlink);
             printf("%d\t",root->data);
            }
               }
      void main()
          {
         struct bst *root;
          int num,choice;
         root =NULL;
         printf("1-->INSERTION\n2-->INORDER\n3-->PREORDER\n4-->POSTORDER\n5-->EXIT\n");
         while(1)
             {
            printf("\nenter your choice:");
            scanf("%d",&choice);
            switch(choice)
                {
               case 1:
                      printf("enter the data of binary tree:");
                      scanf("%d",&num);
                      insert(&root,num);
                      break;
               case 2:
                     inorder(root);
                     break;
               case 3:
                      preorder(root);
                      break;
               case 4:
                     postorder(root);
                     break;
               case 5:
                     exit(0);
               default :
                       printf("\n INVAlID CHOICE\n");
               }
            }
       getch();
         }

No comments:

Post a Comment