F Show Inorder And Preorder Traversal Of A Tree Using C | CodeTheta

Show Inorder And Preorder Traversal Of A Tree Using C

December 21, 2015

/* http://native-code.blogspot.com */
#include<stdio.h>
#include<conio.h>
#include<alloc.h>

#define NULL 0

struct node
 {
   struct node *left;
   int info;
   struct node *right;
 };

void create(struct node **r);
void getnode(struct  node **n);
void preorder(struct node **r);
void inorder(struct node **r);

void main()
{
 struct node *root;
 int top,num;

 create(&root);
 clrscr();

 printf("\n\n\n\t\t Pre Order");
 preorder(&root);

 printf("\n\n\n\t\t In Order");
 inorder(&root);


 getch();

}

void create(struct node **r)
{
 struct node *Pointer,*new,*stack[20];
 int top,num;

 top=0;
 stack[0]=NULL;

 clrscr();

 printf("\n\n\n\t Enter The Root ");
 scanf("%d",&num);
 if(num != 0)
 {
  getnode(&new);
  new->info=num;
  *r=new;
  Pointer=*r;
 }
 else
 *r=NULL;

 while(Pointer != NULL)
 {
  printf("\n\n\n\t Enter The Right Element Of %d :: ",Pointer->info);
  scanf("%d",&num);

  if(num != 0)
  {
   getnode(&new);
   new->info=num;
   Pointer->right=new;
   top++;
   stack[top]=Pointer->right;
  }

  printf("\n\n\n\t Enter The Left Element Of %d :: ",Pointer->info);
  scanf("%d",&num);

  if(num != 0)
  {
   getnode(&new);
   new->info=num;
   Pointer->left=new;
   Pointer=Pointer->left;
  }

  else
  {
   Pointer=stack[top];
   top--;
  }

 }

}

void getnode(struct  node **n)
{
 *n=malloc(sizeof(struct node));
 (*n)->left=NULL;
 (*n)->right=NULL;
 (*n)->info=0;
}

void preorder(struct node **r)
  {
    struct node *Pointer,*stack[20];
    int top;

    top=0;
    stack[top]=NULL;

    Pointer=*r;

    while(Pointer != NULL)
     {
       printf("%d ",Pointer->info);
       if(Pointer->right != NULL)
{
 top++;
 stack[top]=Pointer->right;
}
       if(Pointer->left != NULL)
 Pointer=Pointer->left;
       else
{
 Pointer=stack[top];
 top--;
}
     }
  }

void inorder(struct node **r)
 {
   struct node *Pointer,*stack[20];
   int top;

   top=0;
   stack[top]=NULL;
   Pointer=*r;

   while(Pointer->left != NULL)
    {
      top++;
      stack[top]=Pointer;
      Pointer=Pointer->left;
    }
   while(Pointer != NULL)
    {
      printf("%d ",Pointer->info);
      if(Pointer->right != NULL)
      {
Pointer=Pointer->right;
while(Pointer->left != NULL)
{
  top++;
  stack[top]=Pointer;
  Pointer=Pointer->left;
}
      }
     else
      {
Pointer=stack[top];
top--;
     }

    }
 }
/* http://native-code.blogspot.com */

Try this code in your computer for better understanding. Enjoy the code. If you have any Question you can contact us or mail us.We will reply you as soon as possible.

Post a Comment