Lab 10
Lab 10
Develop a menu driven Program in C for the following operations on Binary Search Tree
(BST) of Integers .
a. Create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2
b. Traverse the BST in Inorder, Preorder and Post Order
c. Search the BST for a given element (KEY) and report the appropriate message
d. Exit
#include <stdio.h>
#include <stdlib.h>
struct BSTNode {
int data;
struct BSTNode *left, *right;
};
return node;
}
int main() {
struct BSTNode* root = NULL;
int choice, key;
int data[] = {6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2};
int n = sizeof(data) / sizeof(data[0]);
for(int i = 0; i < n; i++) {
root = insert(root, data[i]);
}
do {
printf("\nMenu\n");
printf("1. Display Inorder\n");
printf("2. Display Preorder\n");
printf("3. Display Postorder\n");
printf("4. Search\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("Inorder traversal: ");
inorder(root);
break;
case 2:
printf("Preorder traversal: ");
preorder(root);
break;
case 3:
printf("Postorder traversal: ");
postorder(root);
break;
case 4:
printf("Enter the element to search: ");
scanf("%d", &key);
if (search(root, key) != NULL)
printf("Element found\n");
else
printf("Element not found\n");
break;
case 5:
printf("Exiting...\n");
break;
default:
printf("Invalid choice\n");
}
} while (choice != 5);
return 0;
}