Skip to content
StudyFame

Binary Search Tree in C

Searching an unsorted list means checking items one by one. A binary search tree (BST) keeps data in an order that lets you throw away half of the remaining tree at every step, just like binary search on a sorted array, but it also allows fast insertion and deletion.

In this lesson you will learn the BST rule, then write functions to insert, search, find the minimum and maximum, and delete a node in all three cases (leaf, one child, two children). You will also see why inorder traversal of a BST prints values in sorted order.

What You Will Learn

  • The binary search tree property.
  • How to insert a value recursively.
  • How to search for a value.
  • How to find the minimum and maximum.
  • The three cases of deletion and the inorder successor.
  • Time complexity: balanced vs skewed BST.

Binary Search Tree in C Explained

Exam definition: A binary search tree is a binary tree in which, for every node, all values in its left subtree are smaller than the node's value and all values in its right subtree are larger. Both subtrees are also binary search trees. Because of this ordering, search, insertion and deletion take O(h) time, where h is the height: O(log n) for a balanced tree and O(n) in the worst case (a skewed tree). An inorder traversal visits the values in ascending order.

Memory trick: A BST is the game "guess my number". At each node ask: "Is it smaller or bigger?" Smaller → go left, bigger → go right. Every answer cuts the search area roughly in half, so even a million values need only about 20 questions in a balanced tree.

Insert 50, 30, 70, 20, 40, 60, 80:

              50
            /    \
          30      70
         /  \    /  \
       20   40  60   80

Search 60: 60 > 50 -> right; 60 < 70 -> left; found (3 comparisons)
Inorder  : 20 30 40 50 60 70 80   (sorted!)

Syntax: BST Operations

struct tnode
{
    int key;
    struct tnode *left, *right;
};

/* insert: go left if smaller, right if bigger, create the node at a NULL spot */
struct tnode *insert(struct tnode *root, int key);

/* search: compare and move left or right until found or NULL */
struct tnode *search(struct tnode *root, int key);

/* minimum = leftmost node, maximum = rightmost node */
OperationBalanced BSTSkewed BST (worst)
SearchO(log n)O(n)
InsertO(log n)O(n)
DeleteO(log n)O(n)
Inorder traversal (sorted output)O(n)O(n)

Example 1: Insert, Search, Min and Max

#include <stdio.h>
#include <stdlib.h>

struct tnode
{
    int key;
    struct tnode *left, *right;
};

struct tnode *insert(struct tnode *root, int key)
{
    if (root == NULL)
    {
        struct tnode *n = malloc(sizeof *n);
        if (n == NULL)
            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);
    /* equal keys are ignored (no duplicates) */
    return root;
}

struct tnode *search(struct tnode *root, int key, int *steps)
{
    *steps = 0;
    while (root != NULL)
    {
        (*steps)++;
        if (key == root->key)
            return root;
        root = key < root->key ? root->left : root->right;
    }
    return NULL;
}

struct tnode *find_min(struct tnode *t)
{
    while (t != NULL && t->left != NULL)
        t = t->left;
    return t;
}

struct tnode *find_max(struct tnode *t)
{
    while (t != NULL && t->right != NULL)
        t = t->right;
    return t;
}

void inorder(const struct tnode *t)
{
    if (t == NULL)
        return;
    inorder(t->left);
    printf("%d ", t->key);
    inorder(t->right);
}

void free_tree(struct tnode *t)
{
    if (t) { free_tree(t->left); free_tree(t->right); free(t); }
}

int main(void)
{
    int keys[] = {50, 30, 70, 20, 40, 60, 80};
    int targets[] = {60, 20, 65};
    struct tnode *root = NULL;
    int i, steps;

    for (i = 0; i < 7; i++)
        root = insert(root, keys[i]);

    printf("Inorder (sorted): ");
    inorder(root);
    printf("\nMinimum: %d, Maximum: %d\n", find_min(root)->key, find_max(root)->key);

    for (i = 0; i < 3; i++)
    {
        if (search(root, targets[i], &steps) != NULL)
            printf("Search %d: found in %d steps\n", targets[i], steps);
        else
            printf("Search %d: not found (%d steps)\n", targets[i], steps);
    }

    free_tree(root);
    return 0;
}

Output

Inorder (sorted): 20 30 40 50 60 70 80
Minimum: 20, Maximum: 80
Search 60: found in 3 steps
Search 20: found in 3 steps
Search 65: not found (3 steps)

Code Explanation

  1. insert is recursive. If the current spot is empty (NULL), it creates the node there. Otherwise it goes left for a smaller key or right for a bigger key, and stores the returned subtree back in root->left or root->right.
  2. Returning the (possibly new) root lets the first call create the whole tree: root = insert(root, 50).
  3. search is iterative: at each node it either finds the key or moves to one child. Searching 65: 50 → 70 → 60 → right child is NULL, so it is not found after 3 steps.
  4. The minimum is the leftmost node (keep going left); the maximum is the rightmost node.
  5. Inorder (left, node, right) prints the keys in sorted order, a key property of every BST.

How Deletion Works: Three Cases

Case 1: node is a LEAF          -> just remove it.
        delete 20:  30's left becomes NULL

Case 2: node has ONE child      -> replace the node with its child.
        delete 30 (after 20 is gone): 50's left becomes 40

Case 3: node has TWO children   -> find the INORDER SUCCESSOR
        (smallest key in the right subtree), copy its key into the node,
        then delete the successor from the right subtree.
        delete 50:  successor = 60  -> root becomes 60, old 60 node removed

              50                       60
            /    \                   /    \
          30      70      ->       30      70
         /  \    /  \             /  \       \
       20   40  60   80         20   40       80

The inorder successor works because it is bigger than everything on the left and smaller than everything else on the right, so the BST rule still holds. (Using the inorder predecessor, the largest key in the left subtree, also works.)

Example 2: Deleting Nodes from a BST

#include <stdio.h>
#include <stdlib.h>

struct tnode
{
    int key;
    struct tnode *left, *right;
};

struct tnode *insert(struct tnode *root, int key)
{
    if (root == NULL)
    {
        struct tnode *n = malloc(sizeof *n);
        if (n == NULL)
            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;
}

struct tnode *delete_key(struct tnode *root, int key)
{
    struct tnode *t;

    if (root == NULL)
        return NULL;                          /* key not found */
    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)               /* case 1 or 2 */
        {
            t = root->right;
            free(root);
            return t;
        }
        if (root->right == NULL)              /* case 2 */
        {
            t = root->left;
            free(root);
            return t;
        }
        t = root->right;                      /* case 3: inorder successor */
        while (t->left != NULL)
            t = t->left;
        root->key = t->key;
        root->right = delete_key(root->right, t->key);
    }
    return root;
}

void inorder(const struct tnode *t)
{
    if (t) { inorder(t->left); printf("%d ", t->key); inorder(t->right); }
}

void free_tree(struct tnode *t)
{
    if (t) { free_tree(t->left); free_tree(t->right); free(t); }
}

int main(void)
{
    int keys[] = {50, 30, 70, 20, 40, 60, 80};
    struct tnode *root = NULL;
    int i;

    for (i = 0; i < 7; i++)
        root = insert(root, keys[i]);
    printf("Start          : "); inorder(root); printf("\n");

    root = delete_key(root, 20);
    printf("Delete 20 (leaf): "); inorder(root); printf("\n");
    root = delete_key(root, 30);
    printf("Delete 30 (1 child): "); inorder(root); printf("\n");
    root = delete_key(root, 50);
    printf("Delete 50 (2 children): "); inorder(root); printf("\n");
    printf("New root: %d\n", root->key);

    free_tree(root);
    return 0;
}

Output

Start          : 20 30 40 50 60 70 80
Delete 20 (leaf): 30 40 50 60 70 80
Delete 30 (1 child): 40 50 60 70 80
Delete 50 (2 children): 40 60 70 80
New root: 60
  • Deleting 20 (a leaf): the function frees it and returns its right child, NULL, so 30's left becomes NULL.
  • Deleting 30 (now only one child, 40): 30 is replaced by 40.
  • Deleting 50 (two children): the inorder successor is 60 (leftmost in the right subtree). Its key is copied into the root, then the original 60 node is deleted from the right subtree.
  • After every deletion, inorder is still sorted, proving the BST rule is kept.

Important Points to Remember

  • BST rule: left < node < right for every node.
  • Insert and search: smaller → left, bigger → right.
  • Minimum = leftmost; maximum = rightmost.
  • Inorder traversal of a BST gives sorted (ascending) order.
  • Delete: leaf → remove; one child → replace with child; two children → use the inorder successor (or predecessor).
  • Time is O(h): O(log n) if balanced, O(n) if skewed (e.g. inserting sorted data). Self-balancing trees (AVL, red-black) fix this.

Common Mistakes Beginners Make

MistakeWhat happensFix
insert(root->left, key); without assigningNew node is lost; tree never changesroot->left = insert(root->left, key);
Checking only the parent when validating a BSTAccepts invalid trees (e.g. a big value deep in the left subtree)Pass a min/max range down the recursion
Deleting a two-child node by just freeing itBoth subtrees are lostCopy the successor's key, then delete the successor
Inserting already-sorted dataTree becomes a linked list: O(n) operationsInsert in random order or use a balanced tree
Not handling the "not found" case in deleteNULL pointer dereferenceReturn NULL when root is NULL

Binary Search Tree Practice Questions

  1. What is a binary search tree? State its property.
  2. Draw the BST formed by inserting 40, 20, 60, 10, 30, 50.
  3. Explain the three cases of deleting a node from a BST.
  4. Why does inorder traversal of a BST give sorted output?
  5. What is the worst-case time for searching a BST, and when does it occur?
Show answers
  1. A binary tree where every node's left subtree has smaller keys and right subtree has larger keys, recursively.
  2. Root 40; left 20 (children 10, 30); right 60 (left child 50).
  3. Leaf: remove it. One child: replace the node with its child. Two children: replace its key with the inorder successor's (or predecessor's) key and delete that successor.
  4. Inorder visits the left subtree (smaller keys), then the node, then the right subtree (larger keys), at every level.
  5. O(n), when the tree is skewed, for example after inserting keys in sorted order.

Coding Exercise

Write int is_bst(struct tnode *t, int min, int max) that checks whether a binary tree is a valid BST by passing the allowed range down the tree. Test it on a valid BST (50, 30, 70) and on an invalid tree where 30 has a right child 55.

Show solution
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

struct tnode
{
    int key;
    struct tnode *left, *right;
};

struct tnode *node(int k)
{
    struct tnode *n = malloc(sizeof *n);
    if (n == NULL)
        exit(1);
    n->key = k;
    n->left = n->right = NULL;
    return n;
}

int is_bst(const struct tnode *t, int min, int max)
{
    if (t == NULL)
        return 1;
    if (t->key <= min || t->key >= max)
        return 0;
    return is_bst(t->left, min, t->key) && is_bst(t->right, t->key, max);
}

void free_tree(struct tnode *t)
{
    if (t) { free_tree(t->left); free_tree(t->right); free(t); }
}

int main(void)
{
    struct tnode *a = node(50), *b = node(50);
    a->left = node(30);
    a->right = node(70);

    b->left = node(30);
    b->right = node(70);
    b->left->right = node(55);      /* 55 > 50 but is in the left subtree */

    printf("Tree A is %s\n", is_bst(a, INT_MIN, INT_MAX) ? "a BST" : "NOT a BST");
    printf("Tree B is %s\n", is_bst(b, INT_MIN, INT_MAX) ? "a BST" : "NOT a BST");
    free_tree(a);
    free_tree(b);
    return 0;
}
Tree A is a BST
Tree B is NOT a BST

Checking only parent and child would accept tree B (55 > 30), but 55 is in the left subtree of 50, so it breaks the BST rule.

Quick Quiz: Binary Search Tree (MCQ)

  1. In a BST, the left child of a node holds a value that is:

    A) Larger   B) Smaller   C) Equal always   D) Random

  2. Which traversal of a BST gives sorted order?

    A) Preorder   B) Inorder   C) Postorder   D) Level order

  3. The minimum value in a BST is found at the:

    A) Root   B) Rightmost node   C) Leftmost node   D) Any leaf

  4. Deleting a node with two children uses the:

    A) Root   B) Inorder successor   C) Parent   D) Sibling

  5. Worst-case search time in a BST is:

    A) O(1)   B) O(log n)   C) O(n)   D) O(n²)

Show answers
  1. B: smaller.
  2. B: inorder.
  3. C: leftmost node.
  4. B: inorder successor.
  5. C: O(n) (skewed tree).

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

BST ruleLeft < node < right
Search/insertSmaller → left, bigger → right
Min / maxLeftmost / rightmost node
Sorted outputInorder traversal
Delete, 2 childrenUse inorder successor
BalancedO(log n) operations
SkewedO(n) operations

Frequently asked questions

What is a binary search tree?
A binary tree where left subtree keys are smaller and right subtree keys are larger than each node's key.
How do you delete a node with two children in a BST?
Replace its key with the inorder successor (smallest key in the right subtree) and delete the successor.
Why can a BST become slow?
If keys are inserted in sorted order, the tree becomes skewed like a linked list and operations become O(n).

Remember

  • BST = guess my number: smaller left, bigger right.
  • Inorder = sorted.

Next Topic

Next lesson: Tree Traversal in C. You will learn all the ways to visit a tree: inorder, preorder, postorder and level order.