TRAVERSALS
#include<stdio.h>
#include<conio.h>
typedef struct node
{
int data;
struct node*left;
struct node*right;
}tree;
tree* createtree();
tree* insert(tree*,tree*);
void preorder(tree*);
void inorder(tree*);
void postorder(tree*);
void main()
{
int ch;
tree*bt;
clrscr();
bt=createtree();
printf("\n \tBINARY TREE TRAVERSAL \n");
printf("\n \t1.traversals \n");
printf("\n \t2.exit\n");
printf("\n \tenter your choice \n");
scanf("%d",&ch);
if(bt==NULL)
{
printf("\nbinary tree is empty\n");
return;
}
switch(ch)
{
case 1:
printf("\n \t preorder traversal \n");
preorder(bt);
printf("\n \t inorder traversal \n");
inorder(bt);
printf("\n \t postorder traversal \n");
postorder(bt);
break;
case 2:
printf("\n exit");
exit(0);
}
getch();
free(bt);
}
tree* createtree()
{
char ch;
tree *bt=NULL,*temp;
do
{
temp=(tree*)malloc(sizeof(struct node));
printf("\n enter the data\n");
scanf("%d",&temp->data);
temp->left=NULL;
temp->right=NULL;
bt=insert(bt,temp);
fflush(stdin);
printf("\n want to add more data y/n :");
scanf("%c",&ch);
}while((ch=='y')||(ch=='Y'));
return bt;
}
tree* insert(tree *bt,tree *temp)
{
if(bt==NULL)
return temp;
else if(temp->data<bt->data)
bt->left=insert(bt->left,temp);
else if(temp->data>bt->data)
bt->right=insert(bt->right,temp);
else if(temp->data==bt->data)
{
printf("\n data is already existing \n");
return bt;
}
return bt;
}
void inorder(tree *bt)
{
if(bt)
{
inorder(bt->left);
printf("%d",bt->data);
inorder(bt->right);
}
}
void preorder(tree *bt)
{
if(bt)
{
printf("%d",bt->data);
preorder(bt->left);
preorder(bt->right);
}
}
void postorder(tree *bt)
{
if(bt)
{
postorder(bt->left);
postorder(bt->right);
printf("%d",bt->data);
}
}
SAMPLE OUTPUT:
Enter the data
5
Want to add more data y/n: Y
Enter the data
2
Want to add more data y/n: Y
Enter the data
3
Want to add more data y/n: Y
Enter the data
4
Want to add more data y/n: N
BINARY TREE TRAVERSAL
1.traversals
2.exit
Enter your choice
1
Preorder traversal 5234
Inorder traversal 2345
Postorder traversal 4325
Comments
Post a Comment