Data Structures · Trees

Binary search trees

A binary search tree (BST) is a binary tree that keeps its keys in order. That one rule lets search, insert and delete each follow a single path from the root, instead of looking at every node. This page explains the rule, steps through each operation in C++, and lets you build trees and watch what their shape does to the cost.

The BST property

For every node in the tree:

  • every key in its left subtree is smaller than the node's key, and
  • every key in its right subtree is larger.

Both subtrees must be binary search trees too. In this page each key appears at most once; inserting a key that is already there changes nothing.

The rule means one comparison at a node rules out a whole subtree. If you are looking for 7 and the root is 8, everything on the right is larger than 8, so 7 cannot be there.

The rule at the root. Every key on the blue side is less than 8; every key on the yellow side is greater. The same holds at every other node: under 3, 1 is on the left and 6, 4, 7 are on the right.
Stop and think
If every node's left child is smaller than it and its right child is larger, is the tree always a BST?

No. The rule is about whole subtrees, not just children. Picture 8 with left child 3, and 9 as the right child of 3. Each parent and child pair looks fine, but 9 is in 8's left subtree and is larger than 8. A search for 9 would go right at the root and never find it.

Where is the smallest key in a BST? The largest?

The smallest is the leftmost node: keep following left pointers from the root until there is no left child. The largest is the rightmost node. No comparisons are needed.

Searching

Search is naturally recursive. Start at the root and look for key. There are four cases:

  1. The node is nullptr: the key is not in the tree.
  2. The node's key equals key: found it.
  3. key is smaller than the node's key: search the left subtree.
  4. key is larger than the node's key: search the right subtree.
Node* search(Node* root, int key) {
    if (root == nullptr || root->key == key)
        return root;
    if (key < root->key)
        return search(root->left, key);
    return search(root->right, key);
}

Each call moves one level down, so search makes at most h + 1 comparisons, where h is the height of the tree. It takes O(h) time, and the recursion uses O(h) stack space.

Stop and think
In the tree above, try to find 4, 10, 3 and 20. Which nodes do you visit each time?

4: 8, 3, 6, 4 (found after 4 comparisons). 10: 8, 10 (found after 2). 3: 8, 3 (found after 2). 20: 8, 10, 14, then 14's right child is empty, so 20 is not in the tree after 3 comparisons. Try them in the lab below with the "Search example" preset.

A search for a missing key always ends at an empty spot. What is special about that spot?

It is exactly where the key would go if you inserted it. That is why insert is just a search that keeps going until it falls off the tree.

Inserting

A new key is always added as a leaf. Search for it from the root, going left or right at each node, until you reach an empty spot, and put the new node there.

The recursive version returns a pointer to the root of the subtree, and each caller stores that pointer back into its left or right field. At the empty spot it returns the brand new node, and that is how the new node gets linked to its parent.

Node* insertNode(Node* root, int key) {
    if (root == nullptr)
        return new Node(key);
    if (key < root->key)
        root->left = insertNode(root->left, key);
    else if (key > root->key)
        root->right = insertNode(root->right, key);
    return root;      // key already present: unchanged
}
insert 40 →
Inserting 40. 40 < 100, go left; 40 > 20, go right; 40 > 30, and 30 has no right child, so 40 becomes 30's right child.
Stop and think
Why does insertNode return a Node*, and why does the caller write root->left = insertNode(root->left, key)?

When the recursion reaches an empty spot, the parent's left or right pointer must change from nullptr to the new node, but the call only has a copy of that pointer. Returning the new pointer lets the parent store it. For an empty tree the root itself changes, which is why main writes root = insertNode(root, 50).

Insert 10 5 15 2 7 12 20 6 9 18 14 into an empty tree by hand. What is its height?

3. 10 is the root, with 5 and 15 below it. 2 and 7 go under 5, 12 and 20 under 15, then 6 and 9 under 7, 18 under 20 and 14 under 12. Check it with the matching preset in the lab.

Deleting

First search for the node to delete. What happens next depends on how many children it has.

delete 20 →
Case 1: a leaf. Just remove it: its parent's pointer becomes nullptr.
delete 30 →
Case 2: one child. The child moves up and takes the deleted node's place. Everything under 30 was already between 30's parent and its parent's other side, so the BST property still holds.
delete 50 →
Case 3: two children. Find the inorder successor, the smallest key in the right subtree (60). Copy it into the node, then delete the old 60 from the right subtree, which is case 1 or 2.
Stop and think
Why is the inorder successor a good replacement in case 3?

It is larger than everything in the left subtree (it came from the right side) and smaller than everything else in the right subtree (it is the minimum there). So it fits exactly where the deleted key was.

Why can deleting the successor never be case 3 again?

The successor is the leftmost node of the right subtree, so it has no left child. It has at most one child, so deleting it is case 1 or case 2.

Could you use the inorder predecessor instead?

Yes: the largest key in the left subtree (the rightmost node on the left) also fits, and it has no right child. Either works; some implementations alternate between them to keep the tree from leaning to one side.

Try it

Every operation steps through the C++ on the right, with the call stack and the path from the root highlighted.

Presets

The tree

Output

Call stack

    What is happening

    BinarySearchTree.cpp

      The class code, with a search and a maxValueNode added, and with insert leaving an existing key alone.

      Shape is everything

      Every operation walks one path, so its cost is O(h), the height of the tree. What that means depends on the order the keys arrived in:

      OperationTimeBalanced treeSkewed tree
      SearchO(h)O(log n)O(n)
      InsertO(h)O(log n)O(n)
      DeleteO(h)O(log n)O(n)
      Min / maxO(h)O(log n)O(n)
      Inorder traversalO(n)O(n)O(n)
      Stop and think
      Now insert 1 3 5 6 9 12 14 18 20 23 25 (the "Sorted input" preset). What's the problem here?

      Each key is larger than every key before it, so it always goes right. The tree is a single chain of 11 nodes with height 10. Searching for 25 takes 11 comparisons, the same as scanning a list. The order of insertion, not the keys themselves, decided the shape.

      In what order should you insert 1 to 7 to get a perfectly balanced tree?

      Insert the middle first, then the middles of each half: 4, 2, 6, 1, 3, 5, 7. Any order where each node arrives before everything in its subtrees and the middles go first works. Try it with "Build from a list".

      Why does an inorder traversal of a BST print the keys in sorted order?

      Inorder prints the whole left subtree (all smaller keys), then the node, then the whole right subtree (all larger keys). Applied at every node, that is exactly increasing order. This also gives a sort: insert n keys, then traverse, in O(n log n) when the tree stays balanced.

      A BST holds 1,000,000 keys. About how many comparisons does a search make at best, and at worst?

      If the tree is balanced, about 20, since 2²⁰ ≈ 1,000,000. If it is a chain, up to 1,000,000. Self-balancing trees such as AVL and red-black trees restructure themselves on insert and delete to keep the height near log₂ n.