8. bst #include #include // Structure for a tree node struct Node { int data; struct Node *left, *right; }; // Function to create a new node struct Node* createNode(int value) { struct Node *newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->data = value; newNode->left = newNode->right = NULL; return newNode; } // Function to insert a node into BST struct Node* insert(struct Node* root, int value) { if (root == NULL) return createNode(value); if (value < root->data) root->left = insert(root->left, value); else if (value > root->data) root->right = insert(root->right, value); return root; } // Function to search for a node in BST struct Node* search(struct Node* root, int key) { if (root == NULL || root->data == key) return root; if (key < root->data) return search(root->left, key); else return search(root->right, key); } // Inorder traversal (Left, Root, Right) void inorder(struct Node* root) { if (root != NULL) { inorder(root->left); printf("%d ", root->data); inorder(root->right); } } // Preorder traversal (Root, Left, Right) void preorder(struct Node* root) { if (root != NULL) { printf("%d ", root->data); preorder(root->left); preorder(root->right); } } // Postorder traversal (Left, Right, Root) void postorder(struct Node* root) { if (root != NULL) { postorder(root->left); postorder(root->right); printf("%d ", root->data); } } int main() { struct Node* root = NULL; int choice, value, key; struct Node* result; while (1) { printf("\n--- Binary Search Tree Operations ---\n"); printf("1. Insert\n"); printf("2. Inorder Traversal\n"); printf("3. Preorder Traversal\n"); printf("4. Postorder Traversal\n"); printf("5. Search Element\n"); printf("6. Exit\n"); printf("Enter your choice: "); scanf("%d", &choice); switch (choice) { case 1: printf("Enter value to insert: "); scanf("%d", &value); root = insert(root, value); printf("%d inserted into BST.\n", value); break; case 2: printf("Inorder Traversal: "); inorder(root); printf("\n"); break; case 3: printf("Preorder Traversal: "); preorder(root); printf("\n"); break; case 4: printf("Postorder Traversal: "); postorder(root); printf("\n"); break; case 5: printf("Enter value to search: "); scanf("%d", &key); result = search(root, key); if (result != NULL) printf("%d found in the BST.\n", key); else printf("%d not found.\n", key); break; case 6: exit(0); default: printf("Invalid choice! Try again.\n"); } } return 0; }