Binary Search Tree (BST)
Binary Search Tree (BST)
To implement a Binary Search Tree (BST) in C that supports the following operations:
Insertion
Deletion
Finding a node
Finding the minimum and maximum values
Displaying the tree structure
Exiting the program
ALGORITHM
1. Insertion:
o Create a new node if the current node is NULL.
o Compare the new value with the current node's key.
o Recursively insert the value in the left or right subtree based on the
comparison.
2. Deletion:
o Search for the node to be deleted.
o If the node has no children, remove it directly.
o If the node has one child, replace it with its child.
o If the node has two children, find the in-order successor, replace the
node's key with the successor's key, and recursively delete the successor.
3. Find:
o Recursively search the tree based on key comparison.
4. Find Min:
o Traverse to the leftmost node in the tree.
5. Find Max:
o Traverse to the rightmost node in the tree.
6. Display:
o Perform an in-order traversal to print the tree in a hierarchical format
with indentation.
7. Exit:
o Free all allocated memory and terminate the program.
Theory
A Binary Search Tree (BST) is a hierarchical data structure where each node has up to
two children. In a BST:
The left child contains keys less than the node's key.
The right child contains keys greater than the node's key.
In-Order Traversal:
PROGRAM
#include <stdio.h>
#include <stdlib.h>
if (x > root->key) {
root->right = deleteNode(root->right, x);
} else if (x < root->key) {
root->left = deleteNode(root->left, x);
} else {
// Node with only one child or no child
if (root->left == NULL) {
struct BinaryTreeNode* temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
struct BinaryTreeNode* temp = root->left;
free(root);
return temp;
}
displayTree(root->right, space);
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 find: ");
scanf("%d", &value);
temp = findNode(root, value);
if (temp != NULL) {
printf("Node with value %d found.\n", value);
} else {
printf("Node with value %d not found.\n", value);
}
break;
case 4:
temp = findMin(root);
if (temp != NULL) {
printf("Minimum value: %d\n", temp->key);
} else {
printf("Tree is empty.\n");
}
break;
case 5:
temp = findMax(root);
if (temp != NULL) {
printf("Maximum value: %d\n", temp->key);
} else {
printf("Tree is empty.\n");
}
break;
case 6:
printf("Tree structure:\n");
displayTree(root, 0);
printf("\n");
break;
case 7:
freeTree(root);
exit(0);
default:
printf("Invalid choice.\n");
}
}
return 0;
}