Binary Search Tree
Binary Search Tree
h>
#include <stdlib.h>
// Node structure
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Node with two children: Get the inorder successor (smallest in the right
subtree)
struct Node* temp = findMin(root->right);
// Main function
int main() {
struct Node* root = NULL;
int choice, value;
while (1) {
printf("\nBinary Search Tree Operations\n");
printf("1. Insert\n");
printf("2. Delete\n");
printf("3. Search\n");
printf("4. In-order Traversal\n");
printf("5. Pre-order Traversal\n");
printf("6. Post-order Traversal\n");
printf("7. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to insert: ");
scanf("%d", &value);
root = insertNode(root, value);
break;
case 2:
printf("Enter value to delete: ");
scanf("%d", &value);
root = deleteNode(root, value);
break;
case 3:
printf("Enter value to search: ");
scanf("%d", &value);
struct Node* foundNode = searchNode(root, value);
if (foundNode != NULL) {
printf("Value %d found in the tree.\n", foundNode->data);
} else {
printf("Value %d not found in the tree.\n", value);
}
break;
case 4:
printf("In-order Traversal: ");
inOrderTraversal(root);
printf("\n");
break;
case 5:
printf("Pre-order Traversal: ");
preOrderTraversal(root);
printf("\n");
break;
case 6:
printf("Post-order Traversal: ");
postOrderTraversal(root);
printf("\n");
break;
case 7:
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}