A binary search tree keeps for every node: keys in the left subtree are less, keys in the right subtree are greater. This ordering lets search, insert, and delete follow a single path from the root, giving O(h) time. The smallest key is the leftmost node; the largest is the rightmost.
Remember
/* 50
/ \
30 70 left < node < right
/ \ / \
20 40 60 80 */
Reference
Cheat Sheet
Keep these facts handy while you work with Binary Search Trees in C in C.
Topic
Detail
Property
left < node < right
Min
Go left until NULL
Max
Go right until NULL
Cost
O(h)
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Creating a BST in C.
Example 1 — Build a BST and read min and max
Insert seven keys, then walk the extremes.
C
#include <stdio.h>
#include <stdlib.h>
struct T {
int key;
struct T *left, *right;
};
static struct T *mk(int k) {
struct T *t = malloc(sizeof *t);
if (!t) exit(1);
t->key = k;
t->left = t->right = NULL;
return t;
}
static int insert(struct T **root, int k) {
struct T **pp = root;
while (*pp) {
if (k == (*pp)->key) return 0;
pp = k < (*pp)->key ? &(*pp)->left : &(*pp)->right;
}
*pp = mk(k);
return 1;
}
static void inorder(const struct T *t) {
if (!t) return;
inorder(t->left);
printf(" %d", t->key);
inorder(t->right);
}
static void free_tree(struct T *t) {
if (!t) return;
free_tree(t->left);
free_tree(t->right);
free(t);
}
int main(void) {
int keys[] = {50, 30, 70, 20, 40, 60, 80};
struct T *root = NULL;
for (int i = 0; i < 7; i++) insert(&root, keys[i]);
printf("inorder:");
inorder(root);
printf("\n");
struct T *lo = root, *hi = root;
while (lo->left) lo = lo->left;
while (hi->right) hi = hi->right;
printf("min=%d max=%d\n", lo->key, hi->key);
free_tree(root);
return 0;
}
Output
inorder: 20 30 40 50 60 70 80
min=20 max=80
How It Works
The first key becomes the root; each later key follows left or right comparisons.
Inorder shows the keys in sorted order.
Min and max are found without visiting the whole tree.
Edge Cases & Pitfalls
Check these before relying on Binary Search Trees in C in real programs.
order
Insertion order matters
Sorted input produces a chain with O(n) height.
dup
Duplicate policy
Decide whether duplicates are ignored, counted, or stored on one side.
Remember
Key Takeaways
Ordering property.
Search follows one path.
Height decides speed.
One line: A binary search tree keeps for every node: keys in the left subtree are less, keys in the right subtree are greater.
Frequently Asked Questions
For every node, all keys in its left subtree are smaller and all keys in its right subtree are larger.
Start at the root and keep going left until there is no left child.
Continue with "Creating a BST in C" next. Insert keys one at a time, ignore duplicates, and measure the result. The C Trees and Binary Search Trees hub lists every topic in order.