A binary search tree (BST) is a linked structure where every node has up to two children, and every key in the left subtree is smaller than the node while every key in the right subtree is larger. That single rule makes searching, inserting and listing in sorted order fast and simple. It is a favourite topic in data structures courses and interviews. This lesson builds a BST in C with insert, search, traversals, range queries and the trickiest operation, delete.
In this lesson you will learn
- The BST ordering rule and the node structure
- Recursive insert and iterative search
- In-order and pre-order traversal, height, minimum and maximum
- Why inserting sorted data creates an unbalanced tree
- Deleting a leaf, a node with one child and a node with two children
You should know recursion, structures and linked lists.
Insert, Search and Traverse
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int key;
struct Node *left, *right;
} Node;
Node *insert(Node *root, int key) {
if (root == NULL) {
Node *n = malloc(sizeof *n);
if (!n) { perror("malloc"); 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 */
}
Node *search(Node *root, int key, int *steps) {
while (root) {
(*steps)++;
if (key == root->key) return root;
root = key < root->key ? root->left : root->right;
}
return NULL;
}
void inorder(const Node *root) { /* left, node, right = sorted order */
if (!root) return;
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
int height(const Node *root) {
if (!root) return 0;
int l = height(root->left), r = height(root->right);
return 1 + (l > r ? l : r);
}
void free_tree(Node *root) { /* children first, then the node */
if (!root) return;
free_tree(root->left);
free_tree(root->right);
free(root);
}
int main(void) {
int keys[] = {50, 30, 70, 20, 40, 60, 80, 35, 65};
Node *root = NULL;
for (int i = 0; i < 9; i++)
root = insert(root, keys[i]);
printf("in-order: ");
inorder(root);
printf("\nheight: %d\n", height(root));
int ask[] = {65, 45};
for (int i = 0; i < 2; i++) {
int steps = 0;
Node *n = search(root, ask[i], &steps);
printf("search %d: %s after %d comparisons\n", ask[i], n ? "found" : "not found", steps);
}
const Node *lo = root, *hi = root;
while (lo->left) lo = lo->left;
while (hi->right) hi = hi->right;
printf("smallest %d, largest %d\n", lo->key, hi->key);
/* Inserting sorted keys builds a 'stick', not a bushy tree */
Node *stick = NULL;
for (int k = 1; k <= 9; k++) stick = insert(stick, k);
printf("height after inserting 1..9 in order: %d\n", height(stick));
free_tree(root);
free_tree(stick);
return 0;
}
Output
in-order: 20 30 35 40 50 60 65 70 80
height: 4
search 65: found after 4 comparisons
search 45: not found after 3 comparisons
smallest 20, largest 80
height after inserting 1..9 in order: 9
insertwalks left for smaller keys and right for larger ones until it reaches an empty spot, then creates a node there. It returns the (possibly new) root, so the caller writesroot = insert(root, key).- In-order traversal visits the left subtree, then the node, then the right subtree. In a BST this always produces the keys in sorted order.
searchfollows a single path from the root. Finding 65 took 4 comparisons, and proving 45 is missing took only 3, out of 9 keys.- The smallest key is found by going left as far as possible, and the largest by going right.
- The height is the number of levels. The first tree has height 4, but inserting 1 to 9 in order builds a “stick” where each node has only a right child, with height 9. Searching it is no faster than a linked list. Self-balancing trees such as AVL and red-black trees fix this by rotating nodes.
free_treefrees both children before the node itself, a post-order traversal, so no pointer is used after it is freed.
Deleting and Range Queries
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int key;
struct Node *left, *right;
} Node;
Node *new_node(int key) {
Node *n = malloc(sizeof *n);
if (!n) { perror("malloc"); exit(1); }
n->key = key;
n->left = n->right = NULL;
return n;
}
Node *insert(Node *root, int key) {
if (!root) return new_node(key);
if (key < root->key) root->left = insert(root->left, key);
else if (key > root->key) root->right = insert(root->right, key);
return root;
}
Node *delete(Node *root, int key) {
if (!root) return NULL;
if (key < root->key) {
root->left = delete(root->left, key);
} else if (key > root->key) {
root->right = delete(root->right, key);
} else if (!root->left || !root->right) { /* zero or one child */
Node *child = root->left ? root->left : root->right;
free(root);
return child;
} else { /* two children */
Node *succ = root->right; /* smallest key on the right */
while (succ->left) succ = succ->left;
root->key = succ->key;
root->right = delete(root->right, succ->key);
}
return root;
}
void preorder(const Node *r) {
if (!r) return;
printf("%d ", r->key);
preorder(r->left);
preorder(r->right);
}
void print_range(const Node *r, int lo, int hi) { /* skip branches that cannot match */
if (!r) return;
if (lo < r->key) print_range(r->left, lo, hi);
if (lo <= r->key && r->key <= hi) printf("%d ", r->key);
if (r->key < hi) print_range(r->right, lo, hi);
}
void free_tree(Node *r) {
if (!r) return;
free_tree(r->left);
free_tree(r->right);
free(r);
}
int main(void) {
int keys[] = {50, 30, 70, 20, 40, 60, 80, 35, 65};
Node *root = NULL;
for (int i = 0; i < 9; i++) root = insert(root, keys[i]);
printf("pre-order: "); preorder(root); printf("\n");
printf("keys 33 to 66: "); print_range(root, 33, 66); printf("\n");
root = delete(root, 20); /* a leaf */
printf("delete 20 (leaf): "); preorder(root); printf("\n");
root = delete(root, 60); /* one child */
printf("delete 60 (1 child): "); preorder(root); printf("\n");
root = delete(root, 50); /* two children: the root */
printf("delete 50 (root): "); preorder(root); printf("\n");
free_tree(root);
return 0;
}
Output
pre-order: 50 30 20 40 35 70 60 65 80
keys 33 to 66: 35 40 50 60 65
delete 20 (leaf): 50 30 40 35 70 60 65 80
delete 60 (1 child): 50 30 40 35 70 65 80
delete 50 (root): 65 30 40 35 70 80
- Pre-order traversal (node, left, right) prints the root first. It shows the tree’s shape and is the order to use when copying or saving a tree.
print_rangelists keys between 33 and 66 in sorted order, but skips whole branches that cannot contain matches, for example the left side of 30.- Deleting has three cases. A leaf such as 20 is simply freed. A node with one child, 60, is replaced by that child, 65.
- A node with two children, here the root 50, cannot just be removed. Its key is replaced by its in-order successor, the smallest key in its right subtree (65), and that successor is deleted from the right subtree instead. The ordering rule still holds, so 65 is the new root.
- Every function returns the new subtree root, so the parent’s pointer is always updated correctly.
BST Operations
| Operation | Balanced tree | Worst case (a “stick”) |
|---|---|---|
| Search | about log n steps | n steps |
| Insert | about log n steps | n steps |
| Delete | about log n steps | n steps |
| Sorted listing | n steps | n steps |
Common Mistakes
- Calling
insert(root, key)without assigning the result, so the first node is lost. - Freeing a node before its children, which then cannot be reached.
- Handling only leaves in delete and forgetting the two-children case.
- Deep recursion on a stick-shaped tree, which can overflow the stack for very large inputs. Use loops for search, or keep the tree balanced.
Practice Exercises
Exercise 1. Write int count_nodes(const Node *r) and int count_leaves(const Node *r).
Show answer
int count_nodes(const Node *r) {
return r ? 1 + count_nodes(r->left) + count_nodes(r->right) : 0;
}
int count_leaves(const Node *r) {
if (!r) return 0;
if (!r->left && !r->right) return 1;
return count_leaves(r->left) + count_leaves(r->right);
}
Exercise 2. Write a function that checks whether a binary tree really obeys the BST rule.
Show answer
int is_bst(const Node *r, long long lo, long long hi) {
if (!r) 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, LLONG_MIN, LLONG_MAX) */
Checking only each node against its direct children is not enough; every key must fit the range set by all its ancestors.
Frequently Asked Questions
BST or hash table?
A hash table is usually faster for plain lookups. A BST keeps keys in order, so it can list them sorted, find the smallest or largest, and answer range questions such as “all marks between 60 and 80”.
How are duplicates handled?
This lesson ignores them. Other choices are to store a count in each node, or to always send equal keys to one side, for example the right.
Summary
- Left subtree keys are smaller, right subtree keys are larger.
- In-order traversal gives sorted output; post-order is used to free the tree.
- Delete with two children by copying the in-order successor.
- Sorted input makes an unbalanced tree; balanced trees keep operations at about log n.
