#include <stdio.h>
#include <stdlib.h>
struct node {
int item;
struct node * left;
struct node * right;
};
typedef struct node * tptr;
tptr insert(tptr root, int key);
void inorder(tptr root);
void preorder(tptr root);
void postorder(tptr root);
int main() {
int choice, key;
tptr root = NULL;
printf("\n***** BST Operations *****\n");
printf("1.Insert\n");
printf("2.Inorder Display\n");
printf("3.Preorder Display\n");
printf("4.Postorder Display\n");
printf("5.Exit\n");
while (1) {
printf("\nEnter Choice: ");
scanf("%d", & choice);
switch (choice) {
case 1:
printf("Enter Element to be inserted: ");
scanf("%d", & key);
root = insert(root, key);
break;
case 2:
printf("Inorder Traversal :");
inorder(root);
break;
case 3:
printf("Preorder Traversal :");
preorder(root);
break;
case 4:
printf("Postorder Traversal :");
postorder(root);
break;
case 5:
exit(1);
default:
printf("\n...Invalid Choice...\n");
}
}
}
tptr insert(tptr root, int key) {
if (root == NULL) {
tptr p;
p = malloc(sizeof(struct node));
p -> item = key;
p -> left = NULL;
p -> right = NULL;
root = p;
} else if (key < root -> item)
root -> left = insert(root -> left, key);
else if (key > root -> item)
root -> right = insert(root -> right, key);
return root;
}
void inorder(tptr root) {
if (root == NULL)
return;
inorder(root -> left);
printf("%d \t", root -> item);
inorder(root -> right);
}
void preorder(tptr root) {
if (root == NULL)
return;
printf("%d \t", root -> item);
preorder(root -> left);
preorder(root -> right);
}
void postorder(tptr root) {
if (root == NULL)
return;
postorder(root -> left);
postorder(root -> right);
printf("%d \t", root -> item);
}
Note: Need to be arranged in compiler after copied
OutPut:
***** BST Operations *****
1.Insert
2.Inorder Display
3.Preorder Display
4.Postorder Display
5.Exit
Enter Choice: 1
Enter Element to be inserted: 10
Enter Choice: 1
Enter Element to be inserted: 6
Enter Choice: 1
Enter Element to be inserted: 20
Enter Choice: 1
Enter Element to be inserted: 12
Enter Choice: 2
Inorder Traversal :6 10 12 20
Enter Choice: 3
Preorder Traversal :10 6 20 12
Enter Choice: 4
Postorder Traversal :6 12 20 10
Enter Choice: 5