program to traverse a binary tree in order, preorder and post order.
#include<stdio.h>
#include<conio.h>
# define MAX 20
int front=-1,rear=-1,a[MAX];
struct node
{
int info;
struct node *lchild;
struct node *rchild;
}*start,*q;
void inorder(struct node *t)
{
if(t!=NULL)
{
inorder(t->lchild);
printf("%d\t",t->info);
inorder(t->rchild);
}
}
void preorder(struct node *t)
{
if(t!=NULL)
{
printf("%d\t",t->info);
preorder(t->lchild);
preorder(t->rchild);
}
}
void postorder(struct node *t)
{
if(t!=NULL)
{
postorder(t->lchild);
postorder(t->rchild);
printf("%d\t",t->info);
}
}
void create(int num)
{
struct node *new_node;
new_node=(struct node*)malloc(sizeof(struct node));
new_node->info=num;
new_node->lchild=new_node->rchild=NULL;
if(front==-1&&rear==-1)
front=rear=0;
else
rear++;
a[rear]=new_node;
if(start==NULL)
start=q=new_node;
else if(q->lchild==NULL)
q->lchild=new_node;
else if(q->rchild==NULL)
q->rchild=new_node;
else
{
front++;
q=a[front];
if(q->lchild==NULL)
q->lchild=new_node;
else if(q->rchild==NULL)
q->rchild=new_node;
}
}
void main()
{
int n,num,i,op;
start=NULL;
clrscr();
printf("Enter the number of nodes");
scanf("%d",&n);
printf("Enter the nodes");
for (i=0;i<n;i++)
{
scanf("%d",&num);
create(num);
}
printf("ELEMENTS OF TREE:\n");
for(i=0;i<n;i++)
{
q=a[i];
printf("%d\t",q->info);
}
while(1)
{
printf("\n1.INORDER TRAVERSAL\n2.PREORDER TRAVERSAL\n3.POSTORDER TRAVERSAL\n4.EXIT\n");
scanf("%d",&op);
switch(op)
{
case 1:
printf("\nINORDER TRAVERSAL :\n");
inorder(start);
break;
case 2:
printf("\nPREORDER TRAVERSAL :\n");
preorder(start);
break;
case 3:
printf("\nPOSTORDER TRAVERSAL :\n");
postorder(start);
break;
default:
exit(0);
}
}
getch();
}
0 comments:
Post a Comment