A binary search tree (BST) is a binary tree with one extra rule: for every node, all keys in its left subtree are smaller and all keys in its right subtree are larger. That single rule lets you search, insert and delete by walking one path from the root, which takes O(log n) time when the tree is balanced. BSTs underpin ordered maps, sets and database indexes.
In this lesson you will learn
- The BST ordering rule
- Insert and search in C
- Finding the minimum
- The three cases of deletion
- Why insertion order affects speed
BST Operations in C
#include <stdio.h>
#include <stdlib.h>
struct Node { int key; struct Node *left, *right; };
struct Node *insert(struct Node *root, int key) {
if (root == NULL) {
struct Node *n = malloc(sizeof *n);
if (!n) exit(1);
n->key = key; n->left = n->right = NULL;
return n;
}
if (key < root->key) root->left = insert(root->left, key);
else if (key > root->key) root->right = insert(root->right, key);
return root; /* duplicates are ignored */
}
struct Node *search(struct Node *root, int key) {
while (root != NULL && root->key != key)
root = (key < root->key) ? root->left : root->right;
return root;
}
struct Node *min_node(struct Node *root) {
while (root->left) root = root->left;
return root;
}
struct Node *delete_key(struct Node *root, int key) {
if (root == NULL) return NULL;
if (key < root->key) root->left = delete_key(root->left, key);
else if (key > root->key) root->right = delete_key(root->right, key);
else {
if (root->left == NULL || root->right == NULL) { /* 0 or 1 child */
struct Node *child = root->left ? root->left : root->right;
free(root);
return child;
}
struct Node *succ = min_node(root->right); /* 2 children */
root->key = succ->key;
root->right = delete_key(root->right, succ->key);
}
return root;
}
void inorder(const struct Node *r) { if (r) { inorder(r->left); printf("%d ", r->key); inorder(r->right); } }
void free_tree(struct Node *r) { if (r) { free_tree(r->left); free_tree(r->right); free(r); } }
int main(void) {
int keys[] = {50, 30, 70, 20, 40, 60, 80};
struct Node *root = NULL;
for (int i = 0; i < 7; i++) root = insert(root, keys[i]);
printf("Inorder (sorted): "); inorder(root); printf("\n");
printf("Search 60: %s\n", search(root, 60) ? "found" : "not found");
printf("Search 65: %s\n", search(root, 65) ? "found" : "not found");
printf("Minimum: %d\n", min_node(root)->key);
root = delete_key(root, 20); /* leaf */
root = delete_key(root, 30); /* one child */
root = delete_key(root, 50); /* two children: root */
printf("After deleting 20, 30, 50: "); inorder(root); printf("\n");
printf("New root: %d\n", root->key);
free_tree(root);
return 0;
}
Output
Inorder (sorted): 20 30 40 50 60 70 80
Search 60: found
Search 65: not found
Minimum: 20
After deleting 20, 30, 50: 40 60 70 80
New root: 60
- Insert compares the new key with the current node and goes left if it is smaller, right if it is larger, until it finds an empty spot. Duplicates are ignored here; some implementations keep a count instead.
- Search follows the same path and stops at the key or at
NULL. Looking for 65 visits only 50, 70 and 60 before giving up, rather than checking all seven keys. - The minimum is the leftmost node; the maximum is the rightmost.
- An inorder traversal of a BST prints the keys in sorted order.
Deleting a Node: Three Cases
| Case | Example above | What happens |
|---|---|---|
| Leaf (no children) | 20 | Simply remove it |
| One child | 30 (after 20 is gone) | Replace the node with its only child |
| Two children | 50, the root | Copy in the inorder successor (smallest key in the right subtree, 60), then delete that successor from the right subtree |
The successor is the next larger key, so putting it in the deleted node’s place keeps every key on the correct side. That is why 60 becomes the new root.
Insertion Order and Height
#include <stdio.h>
#include <stdlib.h>
struct Node { int key; struct Node *left, *right; };
struct Node *insert(struct Node *r, int key) {
if (!r) {
r = malloc(sizeof *r);
if (!r) exit(1);
r->key = key; r->left = r->right = NULL;
} else if (key < r->key) r->left = insert(r->left, key);
else if (key > r->key) r->right = insert(r->right, key);
return r;
}
int height(const struct Node *r) {
if (!r) return 0;
int a = height(r->left), b = height(r->right);
return 1 + (a > b ? a : b);
}
void free_tree(struct Node *r) { if (r) { free_tree(r->left); free_tree(r->right); free(r); } }
int main(void) {
struct Node *sorted = NULL, *shuffled = NULL;
for (int k = 1; k <= 15; k++) sorted = insert(sorted, k);
int order[] = {8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15};
for (int i = 0; i < 15; i++) shuffled = insert(shuffled, order[i]);
printf("Inserted in sorted order (1..15): height %d\n", height(sorted));
printf("Inserted middle-first: height %d\n", height(shuffled));
free_tree(sorted);
free_tree(shuffled);
return 0;
}
Output
Inserted in sorted order (1..15): height 15
Inserted middle-first: height 4
- Inserting keys already in sorted order sends each one to the right of the last, so the “tree” becomes a linked list of height 15. Search then takes O(n).
- Inserting the same keys middle-first produces a perfectly balanced tree of height 4, so any search takes at most 4 steps.
- Self-balancing trees, such as AVL trees and red-black trees, rotate nodes after updates to keep the height near log₂ n whatever the insertion order.
| Operation | Balanced | Worst (degenerate) |
|---|---|---|
| Search / insert / delete | O(log n) | O(n) |
| Inorder traversal | O(n) | O(n) |
Common Mistakes
- Not assigning the returned pointer:
insert(root, k)instead ofroot = insert(root, k)loses the first node. - Checking only the immediate children when validating a BST; the rule applies to whole subtrees.
- Forgetting to free the removed node during deletion.
- Feeding sorted data into a plain BST and expecting O(log n) performance.
Practice Exercises
Exercise 1. Write a function that checks whether a binary tree is a valid BST.
Show answer
#include <limits.h>
int is_bst(const struct Node *r, long lo, long hi) {
if (r == NULL) return 1;
if (r->key <= lo || r->key >= hi) return 0;
return is_bst(r->left, lo, r->key) && is_bst(r->right, r->key, hi);
}
/* call: is_bst(root, LONG_MIN, LONG_MAX) */
Passing down allowed ranges checks the rule for whole subtrees, not just parent and child.
Exercise 2. Find the k-th smallest key in a BST.
Show answer
Do an inorder traversal and count nodes as you visit them; stop when the count reaches k. It takes O(h + k) time, where h is the height.
Frequently Asked Questions
When should I use a BST instead of a hash table?
Use a BST (usually a balanced one) when you need keys in sorted order, range queries such as “all keys between 10 and 50”, or the nearest larger or smaller key. Hash tables are faster for plain lookups but keep no order.
Can I use the inorder predecessor instead of the successor when deleting?
Yes. The largest key in the left subtree works equally well. Alternating between the two can help keep the tree more balanced over many deletions.
Summary
- BST rule: left subtree smaller, right subtree larger.
- Search, insert and delete follow one root-to-leaf path: O(h).
- Deletion with two children uses the inorder successor.
- Sorted insertions create a tall, slow tree; self-balancing trees fix this.
Next: Heap Data Structure in C.
