DS Lab · Experiment 12
Binary search tree operations
CTreesJNTUH R22 · CS306PC
Aim
To write a menu-driven C program that implements a binary search tree with the operations insert, search, delete (a leaf, a node with one child and a node with two children) and display.
Algorithm
- Each node has
data, aleftpointer and arightpointer. In a binary search tree, every value in a node's left subtree is smaller than the node and every value in its right subtree is larger. - Insert x: if the tree is empty, the new node becomes the root. Otherwise go left if x is smaller than the current node and right if it is larger, until an empty place is found, and attach the new node there.
- Search x: start at the root. If x equals the node, it is found; if x is smaller go left, otherwise go right. If we reach
NULL, x is not in the tree. - Delete x: find the node. Case 1, it is a leaf: remove it. Case 2, it has one child: replace the node by that child.
- Case 3, it has two children: find the inorder successor (the smallest node in the right subtree), copy its value into the node, and remove the successor from the right subtree.
- Display: print the inorder traversal (sorted order) and the tree turned sideways.
- Repeat the menu until Exit, then free every node.
Program
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *left, *right;
};
struct node *new_node(int value) {
struct node *n = malloc(sizeof(struct node));
if (n == NULL) {
printf("Memory not available\n");
exit(1);
}
n->data = value;
n->left = n->right = NULL;
return n;
}
struct node *insert(struct node *root, int value) {
if (root == NULL) {
return new_node(value);
}
if (value < root->data) {
root->left = insert(root->left, value);
} else if (value > root->data) {
root->right = insert(root->right, value);
} else {
printf("%d is already in the tree\n", value);
}
return root;
}
int search(struct node *root, int value) {
while (root != NULL) {
if (value == root->data) {
return 1;
}
root = (value < root->data) ? root->left : root->right;
}
return 0;
}
/* Remove the smallest node of a subtree (it has no left child) */
struct node *remove_min(struct node *root) {
if (root->left == NULL) {
struct node *right = root->right;
free(root);
return right;
}
root->left = remove_min(root->left);
return root;
}
struct node *delete_node(struct node *root, int value) {
if (root == NULL) {
printf("%d not found in the tree\n", value);
return NULL;
}
if (value < root->data) {
root->left = delete_node(root->left, value);
} else if (value > root->data) {
root->right = delete_node(root->right, value);
} else if (root->left == NULL && root->right == NULL) {
printf("Deleted %d (case 1: leaf node)\n", value);
free(root);
return NULL;
} else if (root->left == NULL || root->right == NULL) {
struct node *child = (root->left != NULL) ? root->left : root->right;
printf("Deleted %d (case 2: one child, replaced by %d)\n", value, child->data);
free(root);
return child;
} else {
struct node *succ = root->right;
while (succ->left != NULL) { /* smallest value in right subtree */
succ = succ->left;
}
printf("Deleted %d (case 3: two children, replaced by inorder successor %d)\n",
value, succ->data);
root->data = succ->data;
root->right = remove_min(root->right);
}
return root;
}
void inorder(struct node *root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
/* Print the tree turned 90 degrees: root on the left, right subtree on top */
void print_tree(struct node *root, int level) {
if (root == NULL) {
return;
}
print_tree(root->right, level + 1);
for (int i = 0; i < level; i++) {
printf(" ");
}
printf("%d\n", root->data);
print_tree(root->left, level + 1);
}
void display(struct node *root) {
if (root == NULL) {
printf("Tree is empty\n");
return;
}
printf("Inorder: ");
inorder(root);
printf("\nTree (turned sideways, root on the left):\n");
print_tree(root, 0);
}
void free_tree(struct node *root) {
if (root != NULL) {
free_tree(root->left);
free_tree(root->right);
free(root);
}
}
int main(void) {
struct node *root = NULL;
int choice, value, count;
printf("BINARY SEARCH TREE\n");
printf("1. Insert\n2. Search\n3. Delete\n4. Display\n5. Exit\n");
do {
printf("\nEnter your choice: ");
if (scanf("%d", &choice) != 1) {
printf("Invalid input\n");
break;
}
switch (choice) {
case 1:
printf("How many values? ");
if (scanf("%d", &count) != 1 || count < 1) {
printf("Invalid count\n");
break;
}
printf("Enter %d values: ", count);
for (int i = 0; i < count && scanf("%d", &value) == 1; i++) {
root = insert(root, value);
}
break;
case 2:
printf("Enter value to search: ");
if (scanf("%d", &value) == 1) {
printf("%d is %s\n", value, search(root, value) ? "found" : "not found");
}
break;
case 3:
printf("Enter value to delete: ");
if (scanf("%d", &value) == 1) {
root = delete_node(root, value);
}
break;
case 4:
display(root);
break;
case 5:
break;
default:
printf("Invalid choice\n");
}
} while (choice != 5);
free_tree(root);
printf("All nodes freed. Exiting.\n");
return 0;
}Output
BINARY SEARCH TREE
1. Insert
2. Search
3. Delete
4. Display
5. Exit
Enter your choice: 1
How many values? 7
Enter 7 values: 50 30 70 20 40 60 80
Enter your choice: 4
Inorder: 20 30 40 50 60 70 80
Tree (turned sideways, root on the left):
80
70
60
50
40
30
20
Enter your choice: 2
Enter value to search: 40
40 is found
Enter your choice: 2
Enter value to search: 65
65 is not found
Enter your choice: 3
Enter value to delete: 20
Deleted 20 (case 1: leaf node)
Enter your choice: 3
Enter value to delete: 30
Deleted 30 (case 2: one child, replaced by 40)
Enter your choice: 3
Enter value to delete: 50
Deleted 50 (case 3: two children, replaced by inorder successor 60)
Enter your choice: 3
Enter value to delete: 99
99 not found in the tree
Enter your choice: 4
Inorder: 40 60 70 80
Tree (turned sideways, root on the left):
80
70
60
40
Enter your choice: 5
All nodes freed. Exiting.Recorded by compiling and running this exact program. Typed input appears after each prompt.
How it works
The sideways picture is the tree rotated a quarter turn anticlockwise: the root is at the left edge, its right subtree is above it and its left subtree below it. Tilt your head to the left to see the usual shape.
The run deletes 20 (a leaf), then 30 (which now has only the child 40), then the root 50 (two children). In the last case 60, the smallest value in the right subtree, takes 50's place, so the tree stays a valid binary search tree.
Common mistakes
In case 3, copying the successor's value and then forgetting to delete the successor node, so the value appears twice in the tree.
Not storing the return value of
delete_nodeorinsertback intoroot(orroot->left/root->right). The link to the changed subtree is lost.Taking the largest value of the right subtree instead of the smallest. The inorder successor is found by going right once and then left as far as possible.
Inserting equal values on both sides inconsistently. Decide how duplicates are handled; this program rejects them.
Viva questions
Try to answer each one aloud before you open it.
What is a binary search tree?
A binary tree in which, for every node, all values in the left subtree are smaller than the node's value and all values in the right subtree are larger.
What are the three cases when deleting a node?
The node is a leaf: just remove it. The node has one child: link its parent directly to that child. The node has two children: replace its value with its inorder successor (or predecessor) and delete that node instead.
What is the inorder successor of a node?
The next larger value in the tree. For a node with a right child, it is the leftmost node of the right subtree.
What is the time complexity of search, insert and delete?
O(h), where h is the height of the tree. That is O(log n) for a balanced tree but O(n) in the worst case, when the tree becomes a chain.
When does a binary search tree become skewed, and how is it fixed?
When values are inserted in sorted order, each new node goes to the same side and the tree becomes a linked list. Self-balancing trees such as AVL and red-black trees fix this by rotations.
Learn the concepts
- Binary Search Trees (BST) in Python: Insert, Search and Delete
- Trees and Binary Trees: Terminology and Python Implementation
- Tree Traversals: Preorder, Inorder, Postorder and Level Order
- Dynamic Memory Allocation in C: malloc, calloc, realloc and free
- Recursion in C: Base Case, Recursive Case and Classic Examples