#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct TreeNode;
typedef struct TreeNode *node;
typedef int ElementType;
struct TreeNode
{
int element;
node left, right;
}*root;
node insert(ElementType x,node t)
{
if(t==NULL)
{
t = malloc(sizeof(node));
t->element = x;
t->left = t->right = NULL;
}
else
{
if(x < t->element)
t->left = insert(x, t->left);
else if(x > t->element)
t->right = insert(x, t->right);
}
return t;
}
void printpreorder(node T)
{
if(T != NULL)
{
printf("%d ", T->element);
printpreorder(T->left);
printpreorder(T->right);
}
}
void printinorder(node T)
{
if(T != NULL)
{
printinorder(T->left);
printf("%d ", T->element);
printinorder(T->right);
}
}
void printpostorder(node T)
{
if(T != NULL)
{
printpostorder(T->left);
printpostorder(T->right);
printf("%d ", T->element);
}
}
void main()
{
int ch;
ElementType a;
root = NULL;
while(1)
{
clrscr();
printf("\n1. Insert\n2. Print Pre Order\n3. Print In Order\n4. Print Post Order\n5. Exit\nEnter Your Choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter an element : ");
scanf("%d", &a);
root = insert(a, root);
break;
case 2:
printpreorder(root);
break;
case 3:
printinorder(root);
break;
case 4:
printpostorder(root);
break;
case 5:
exit(0);
default:
printf("Invalid Choice");
}
getch();
}
}
Sample Output:
1. Insert
2. Print Pre Order
3. Print In Order
4. Print Post Order
5. Exit
Enter Your Choice : 1
Enter an Element : 1
2. Print Pre Order
3. Print In Order
4. Print Post Order
5. Exit
Enter Your Choice : 1
Enter an Element : 1
1. Insert
2. Print Pre Order
3. Print In Order
4. Print Post Order
5. Exit
Enter Your Choice : 1
Enter an Element : 5
2. Print Pre Order
3. Print In Order
4. Print Post Order
5. Exit
Enter Your Choice : 1
Enter an Element : 5
1. Insert
2. Print Pre Order
3. Print In Order
4. Print Post Order
5. Exit
Enter Your Choice : 1
Enter an Element : 2
2. Print Pre Order
3. Print In Order
4. Print Post Order
5. Exit
Enter Your Choice : 1
Enter an Element : 2
1. Insert
2. Print Pre Order
3. Print In Order
4. Print Post Order
5. Exit
Enter Your Choice : 1
Enter an Element : 7
2. Print Pre Order
3. Print In Order
4. Print Post Order
5. Exit
Enter Your Choice : 1
Enter an Element : 7
1. Insert
2. Print Pre Order
3. Print In Order
4. Print Post Order
5. Exit
Enter Your Choice : 2
1 2 5 7
2. Print Pre Order
3. Print In Order
4. Print Post Order
5. Exit
Enter Your Choice : 2
1 2 5 7
1. Insert
2. Print Pre Order
3. Print In Order
4. Print Post Order
5. Exit
Enter Your Choice : 3
1 5 2 7
2. Print Pre Order
3. Print In Order
4. Print Post Order
5. Exit
Enter Your Choice : 3
1 5 2 7
1. Insert
2. Print Pre Order
3. Print In Order
4. Print Post Order
5. Exit
Enter Your Choice : 4
2 7 5 1
2. Print Pre Order
3. Print In Order
4. Print Post Order
5. Exit
Enter Your Choice : 4
2 7 5 1
1. Insert
2. Print Pre Order
3. Print In Order
4. Print Post Order
5. Exit
Enter Your Choice : 5
2. Print Pre Order
3. Print In Order
4. Print Post Order
5. Exit
Enter Your Choice : 5