Tuesday, October 26, 2010

C Program to demostrate Binary Tree traversal using recursion

#include<stdio.h>
#include<conio.h>
#include<alloc.h>

struct NODE
{
   int data;
   struct NODE *leftchild;
   struct NODE *rightchild;
};

struct NODE *Binary_Tree(char *,int,int);
void display(struct NODE *,int);
void Pre_order(struct NODE *);
void In_order(struct NODE *);
void Post_order(struct NODE *);

/* Function to create a binary tree */
struct NODE * Binary_Tree(char *List,int Lower,int Upper)
{
  struct NODE *Node;
  int Mid=(Lower + Upper)/2;

  Node=(struct NODE*)malloc(sizeof(struct NODE));
  Node->data=List[Mid];

  if(Lower>=Upper)
  {
    Node->leftchild=NULL;
    Node->rightchild=NULL;
    return(Node);
  }

  if(Lower <=Mid-1)
     Node->leftchild=Binary_Tree(List,Lower,Mid-1);
  else
     Node->leftchild=NULL;

  if(Mid+1<=Upper)
     Node->rightchild=Binary_Tree(List,Mid+1,Upper);
  else
     Node->rightchild=NULL;

  return(Node);
}

/* Output function */
void display(struct NODE *T,int Level)
{
   int i;
   if(T)
   {
      display(T->rightchild,Level+1);
      printf("\n");
      for(i=0;i<Level;i++)
 printf("   ");
      printf(" %d",T->data);
      display(T->leftchild,Level+1);
   }
}

/* Pre-order traversal */
void Pre_order(struct NODE *Node)
{
  if(Node)
  {
     printf(" %d",Node->data);
     Pre_order(Node->leftchild);
     Pre_order(Node->rightchild);
  }
}


/* In-order traversal */
void In_order(struct NODE *Node)
{
  if(Node)
  {
    In_order(Node->leftchild);
    printf(" %d",Node->data);
    In_order(Node->rightchild);
  }
}

/* Post-order traversal */
void Post_order(struct NODE *Node)
{
  if(Node)
  {
     Post_order(Node->leftchild);
     Post_order(Node->rightchild);
     printf(" %d",Node->data);
  }
}

/* Function Main */
void main()
{
   char List[100];
   int Number=0;
   int info;
   char choice;

   struct NODE *T=(struct NODE*)malloc(sizeof(struct NODE));
   T=NULL;
   printf("\n Input Choice 'b' to break : ");
   choice=getchar();
   fflush(stdin);
   while(choice != 'b')
   {
      printf("\n Input information of the node : ");
      scanf("%d",&info);
      List[Number++]=info;
      fflush(stdin);
      printf("\n Input choice 'b' to break : ");
      choice=getchar();
      fflush(stdin);
   }
   Number--;
   printf("\n Number of elements in the list is %d ",Number);
   T=Binary_Tree(List,0,Number);
   display(T,1);
   printf("\n Pre-order traversal \n");
   Pre_order(T);
   printf("\n In-order traversal \n");
   In_order(T);
   printf("\n Post-order traversal \n");
   Post_order(T);
}






No comments:

Post a Comment