Skip to content
Codescope

Binary search trees

One ordering rule turns searching into a sequence of yes/no decisions.

core11 min9 steps

Before you start

A **binary search tree** (BST) is a tree of nodes where every node holds a value and has up to two children. The magic rule: everything in the *left* subtree is smaller, everything in the *right* subtree is larger.

That single rule turns searching into a sequence of yes/no decisions. Each step down the tree halves the values still in play, which is why a balanced BST of a million nodes is only about 20 levels deep.

This lesson watches keys get inserted into a BST one by one, each walking down to its correct place, then watches search discard entire subtrees on every comparison.

Binary search tree

left subtree < node < right subtree
50

The invariant is what makes the tree searchable. Break it and it is just a tree.

Step 1 of 9. The first key becomes the root. An empty tree is a `NULL` pointer. Inserting 50 into it allocates one node with two null children. Everything that follows is governed by a single invariant: **every key in the left subtree is smaller than the node, and every key in the right subtree is larger**.

01 / 09

Step 01 / 09

The first key becomes the root

An empty tree is a NULL pointer. Inserting 50 into it allocates one node with two null children.

Everything that follows is governed by a single invariant: **every key in the left subtree is smaller than the node, and every key in the right subtree is larger**.

binary-search-trees.cC
struct Node {    int          key;    struct Node *left, *right;};struct Node *insert(struct Node *root, int key) {    if (root == NULL)        return make_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;                 /* equal: already present */}struct Node *search(struct Node *root, int key) {    while (root != NULL) {        if (key == root->key) return root;        root = (key < root->key) ? root->left : root->right;    }    return NULL;}