Tuesday, 8 April 2014

/*write a program to perform in order, pre order and post order traversal of a binary search tree*/
#include<stdio.h>
#include<stdlib.h>
struct link_list
{
int data;
struct link_list *rchild;
struct link_list *lchild;
}*ROOT=NULL;

typedef struct link_list node;
node *current,*nnew;

node * insert(int a)
{
       nnew=malloc(sizeof(node));
       nnew->data=a;
    nnew->rchild=NULL;
    nnew->lchild=NULL;
    return nnew;
}
void create(int elem)
 {
       int count=-1;
         while(count!=0)
          {
            if(ROOT==NULL)
              {
               ROOT=insert(elem);
               current=ROOT;
               count++;
              }
            else
             {
                 if(elem>current->data)
                  {
                        if(current->rchild==NULL)
                        {
                      current->rchild=insert(elem);
                     current=ROOT;
                     count++;
                        }
                        else
                               current=current->rchild;
                  }
                 else
                  {
                        if(current->lchild==NULL)
                              {
                            current->lchild=insert(elem);
                         current=ROOT;
                         count++;
                         }
                        else
                               current=current->lchild;
                  }
               }
          }
       }


void inorder(node *temp)
{

 if(temp != NULL)
 {
    inorder(temp->lchild);
       printf(" %3d",temp->data);
       inorder(temp->rchild);
 }
}
void preorder(node *temp)
{

 if(temp != NULL)
 {
        printf(" %3d",temp->data);
        preorder(temp->lchild);
        preorder(temp->rchild);
 }
}

void postorder(node *temp)
{

 if(temp != NULL)
 {
        postorder(temp->lchild);
        postorder(temp->rchild);
       printf(" %3d",temp->data);
 }
}
int main()
{
       int ar,i,limit;

       printf("elements how many elements you want to enter? ");
       scanf("%d",&limit);

       printf("enter the elements\n");

       for(i=0;i<limit;i++)
        {
         scanf("%d",&ar);
         create(ar);
        }

       printf("\n*****inorder traversal*****\n\n");
       inorder(ROOT);
       printf("\n*****preorder traversal*****\n\n");
       preorder(ROOT);
       printf("\n*****postorder traversal*****\n\n");
       postorder(ROOT);

       return 0;

}


No comments:

Post a Comment