Binary Search Trees

Data Structures & Algorithms · Trees & Heaps · Intermediate · 22 min

Search, insert and delete in a binary search tree, get sorted order from an inorder walk, and validate a BST with min/max bounds.

A road with a signpost at every junction: 'smaller numbers, turn left; bigger numbers, turn right'. Following the signs from the top takes you straight to your number, or to the empty spot where it belongs.

The idea in everyday words

Playing 'guess my number' with a friend who answers 'lower' or 'higher'. A BST stores the answers to those questions in advance: the root is your first guess, its left side holds everything lower and its right side everything higher. Each step down the tree is one guess, so a well-shaped tree of a million keys finds anything in about 20 guesses.

The one rule

A binary search tree (BST) is a binary tree (each node has at most two children) with one rule at every node:

everything in the left subtree is smaller, everything in the right subtree is bigger.

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

Notice the rule is about whole subtrees, not just children: 40 is in 50's left subtree, so it must be smaller than 50 as well as bigger than 30.

This rule turns the tree into a frozen binary search. At each node you compare once and throw away a whole side.

Search and insert: follow the signposts

Search for key k: start at the root. If k equals the node, found. If smaller, go left; if bigger, go right. If you fall off the tree (reach None), k is not there.

Insert k: do the same walk. The None you fall off is exactly where k belongs. Hang a new node there.

def insert(root, key):
    if root is None:
        return Node(key)              # the empty spot we were looking for
    if key < root.key:
        root.left = insert(root.left, key)
    elif key > root.key:
        root.right = insert(root.right, key)
    return root                       # duplicates are ignored

Cost: O(h), where h is the height (the longest root-to-leaf path).

Tree shape Height h Search
bushy, balanced about log₂ n O(log n)
a straight line (insert 1, 2, 3, 4...) n O(n), as slow as a list

Keeping h small is the job of balanced trees (next lesson).

Inorder walk = sorted order

An inorder traversal visits left subtree, then the node, then the right subtree.

In a BST that means: everything smaller, then me, then everything bigger. So it lists the keys in sorted order, for free.

def inorder(node):
    if node is None:
        return []
    return inorder(node.left) + [node.key] + inorder(node.right)

The tree above gives [20, 30, 40, 50, 60, 70, 80].

This unlocks many questions: k-th smallest (stop after k visits), range queries (all keys between 35 and 65, skipping subtrees that cannot overlap), and validate a BST (the inorder list must be strictly increasing).

Delete: three cases

First find the node, then:

  1. Leaf (no children): just remove it. Deleting 20 above: 30's left becomes None.
  2. One child: splice it out. The child moves up and takes its place. The BST rule still holds because that whole subtree was already on the correct side of the parent.
  3. Two children: you cannot simply remove it, two subtrees would be orphaned. Instead, copy in its inorder successor (the smallest key in its right subtree: go right once, then left as far as possible), then delete the successor from the right subtree. The successor has no left child, so that second delete is case 1 or 2.

Deleting 50: the successor is 60. 60 moves to the root, and the old 60 leaf is removed. Every key left of the root is still smaller than 60, and everything right is still bigger.

(The inorder predecessor, the largest key in the left subtree, works just as well.)

Validating a BST: pass the bounds down

The tempting check, "each left child is smaller and each right child is bigger", is wrong:

      5
     / \
    4   6
       / \
      3   7

Every parent/child pair looks fine, but 3 is in 5's right subtree and is smaller than 5. Not a BST.

Fix: as you walk down, carry the allowed range (low, high) for that position.

  • The root may be anything: (-∞, +∞).
  • Going left from node v: the ceiling becomes v, (low, v).
  • Going right from node v: the floor becomes v, (v, high).

At 5 → 6 → 3, the range for 3 is (5, 6) and 3 fails. Each node is checked once: O(n).

Step by step

  1. Start:

    Tree built from 50, 30, 70, 20, 40, 60, 80. Insert 45.

  2. At 50:

    45 < 50, so 45 belongs in the left subtree. Go left. The whole right side (60, 70, 80) is never looked at.

  3. At 30:

    45 > 30, go right.

  4. At 40:

    45 > 40, go right. 40 has no right child: this empty spot is where 45 belongs. Attach it as 40's right child.

  5. Search 65:

    65 > 50 → right to 70. 65 < 70 → left to 60. 65 > 60 → right, but 60 has no right child. Not found, after only 3 comparisons.

  6. Inorder check:

    Left, node, right gives 20, 30, 40, 45, 50, 60, 70, 80: still sorted, so the insert kept the BST rule.

Code example

class Node:
    def __init__(self, key):
        self.key, self.left, self.right = key, None, None

def insert(root, key):
    if root is None:
        return Node(key)
    if key < root.key:
        root.left = insert(root.left, key)
    elif key > root.key:
        root.right = insert(root.right, key)
    return root

def search_path(root, key):
    path = []
    while root:
        path.append(root.key)
        if key == root.key:
            return "found via " + str(path)
        root = root.left if key < root.key else root.right
    return "missing, checked " + str(path)

def inorder(root):
    return inorder(root.left) + [root.key] + inorder(root.right) if root else []

def delete(root, key):
    if root is None:
        return None
    if key < root.key:
        root.left = delete(root.left, key)
    elif key > root.key:
        root.right = delete(root.right, key)
    else:
        if root.left is None:          # leaf or only a right child
            return root.right
        if root.right is None:         # only a left child
            return root.left
        succ = root.right              # two children: inorder successor
        while succ.left:
            succ = succ.left
        root.key = succ.key
        root.right = delete(root.right, succ.key)
    return root

root = None
for k in [50, 30, 70, 20, 40, 60, 80, 45]:
    root = insert(root, k)
print("inorder:", inorder(root))
print("search 60:", search_path(root, 60))
print("search 65:", search_path(root, 65))
root = delete(root, 20)                # case 1: leaf
root = delete(root, 40)                # case 2: one child (45)
root = delete(root, 50)                # case 3: two children
print("after deletes:", inorder(root), "new root:", root.key)

Complexity

  • Time: Search, insert, delete: O(h), which is O(log n) for a balanced tree and O(n) for a skewed one. Validating or an inorder walk: O(n), each node once
  • Space: O(h) for the recursion stack (O(n) worst case for a skewed tree), plus the n nodes themselves

Interview tips

  • Clarify duplicates and whether the BST is strict before coding. It changes < versus <=.

  • For 'validate BST', mention the children-only trap explicitly and then give the bounds solution. Mention the inorder alternative too.

  • State complexity as O(h), then explain h = log n only if balanced. Interviewers check that you know a BST can degrade to O(n).

  • For delete, walk through all three cases on a small drawing, especially the successor case.

  • Common follow-ups: k-th smallest (inorder with a counter), lowest common ancestor in a BST (split point of the two keys), convert a sorted array to a balanced BST (pick the middle as the root).

Challenge: Is It a Valid BST?

A binary tree is given as a level-order list (None / null means no child), like LeetCode. Return True if it is a valid binary search tree: every node is strictly greater than all keys in its left subtree and strictly smaller than all keys in its right subtree. An empty tree is valid.

A build(level) helper is provided.

Example: is_valid_bst([5, 1, 4, None, None, 3, 6]) → False (4 is in 5's right subtree but smaller than 5)

Keys can be any integers: zero, negative, or as big as 2147483647.

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Trees & Heaps

Previous: Trees, DFS & BFS · Next: Balanced Trees: AVL & Red-Black