Binary Search Tree of Integers to Create and Traverse the BST in Inorder Preorder and Post Order in c program and 3rd Sem Data Structure and Application lab 8th program
Design, Develop and Implement a menu driven Program in C for the following operations on Binary Search Tree (BST) of Integers
a. Create a BST of N Integers
b. Traverse the BST in Inorder, Preorder and Post Order
/* Design, Develop and Implement a menu driven Program in C for the following operations on Binary Search Tree (BST) of Integers
a. Create a BST of N Integers
b. Traverse the BST in Inorder, Preorder and Post Order */
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *left;
struct Node *right;
};
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct Node* insert(struct Node* node, int data) {
if (node == NULL) {
return createNode(data);
}
if (data < node->data) {
node->left = insert(node->left, data);
} else if (data > node->data) {
node->right = insert(node->right, data);
}
return node;
}
void inorderTraversal(struct Node* node) {
if (node == NULL) {
return;
}
inorderTraversal(node->left);
printf("%d ", node->data);
inorderTraversal(node->right);
}
void preorderTraversal(struct Node* node) {
if (node == NULL) {
return;
}
printf("%d ", node->data);
preorderTraversal(node->left);
preorderTraversal(node->right);
}
void postorderTraversal(struct Node* node) {
if (node == NULL) {
return;
}
postorderTraversal(node->left);
postorderTraversal(node->right);
printf("%d ", node->data);
}
int main() {
struct Node* root = NULL;
int choice, data, n;
printf("Enter the number of elements in the BST: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("Enter an element to insert: ");
scanf("%d", &data);
root = insert(root, data);
}
while (1) {
printf("\nBinary Search Tree Operations:\n");
printf("1. Inorder Traversal\n");
printf("2. Preorder Traversal\n");
printf("3. Postorder Traversal\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Inorder Traversal: ");
inorderTraversal(root);
break;
case 2:
printf("Preorder Traversal: ");
preorderTraversal(root);
break;
case 3:
printf("Postorder Traversal: ");
postorderTraversal(root);
break;
case 4:
exit(0);
default:printf("Invalid ");
}
}
}
