Treetraversal
Treetraversal
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<alloc.h>
struct tree
{ int data;
struct tree *right,*left;
};
typedef struct tree node;
node *t=NULL;
node* insert(int x,node *t)
{
if(t==NULL)
{
t=(node*)malloc(sizeof(node));
t->data=x;
t->left=NULL;
t->right=NULL;
}
else
if(x<t->data)
t->left=insert(x,t->left);
else
if(x>t->data)
t->right=insert(x,t->right);
return t;
}
void inorder(node *t)
{
if(t!=NULL)
{
inorder(t->left);
printf(" %d",t->data);
inorder(t->right);
}
}
void preorder(node *t)
{
if(t!=NULL)
{
printf(" %d",t->data);
preorder(t->left);
preorder(t->right);
}
}
void main()
{
int data,ch,s;
char c;
while(1)
{
clrscr();
printf("\n1.Insert");
printf("\n2.Inorder Traversal");
printf("\n3.Preorder Traversal");
printf("\n4.Postorder Traversal");
printf("\n5.Exit");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{ case 1: printf("\nEnter data to be inserted:");
scanf("%d",&data);
t=insert(data,t);
break;
case 2: printf("\nThe Inorder Display:\n");
inorder(t);
break;
case 3: printf("\nThe Preorder Display:\n");
preorder(t);
break;
case 4: printf("\nThe Postorder Display:\n");
postorder(t);
break;
case 5: exit(0);
default:printf("\nEnter valid option");
}
getch();
}
}
OUTPUT: