BST LL PGM
BST LL PGM
h>
#include <stdlib.h>
struct Node {
int data;
struct Node *left, *right;
};
struct Node* newNode(int item) {
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
struct Node* insert(struct Node* node, int data) {
if (node == NULL)
return newNode(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 inorder(struct Node* root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
int main() {
struct Node* root = NULL;
int choice, data, key;
while (1) {
printf("\nMenu:\n");
printf("1. Insert\n");
printf("2. Inorder Traversal\n");
printf("3. Search\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter data to insert: ");
scanf("%d", &data);
root = insert(root, data);
break;
case 2:
printf("Inorder traversal: ");
inorder(root);
printf("\n");
break;
case 3:
printf("Enter key to search: ");
scanf("%d", &key);
struct Node* result = search(root, key);
if (result != NULL)
printf("Key %d found.\n", key);
else
printf("Key %d not found.\n", key);
break;
case 4:
exit(0);
default:
printf("Invalid choice.\n");
}
}
return 0;
}