Skip to content
Visual explainer 3h 30m to learn 5 steps

Binary search trees

Implement BST search, insert and delete and explain why balance matters.

By Invicly Tech, , in Data Structures & Algorithms. About 11 minutes to read.

Topic 26 of 54

In short

A binary search tree keeps every left descendant smaller and every right descendant larger than the node. Search, insert and delete follow one root-to-leaf path, so they cost O(h). If keys arrive in sorted order the tree degenerates into a linked list and h becomes n.

Explained simply

A binary search tree, or BST, is a binary tree with one sorting rule. Everything in a node's left subtree is smaller than the node, and everything in its right subtree is larger. That rule holds at every node, not just between a parent and its direct children.

Searching works like a number guessing game. Start at the root. If your key is smaller, go left; if larger, go right. Each step drops a whole subtree from consideration. You either find the key or fall off the bottom, which means it is not there.

Inserting is the same walk: when you fall off the bottom, attach the new node right there. Deleting is trickier when the node has two children, but there is a neat trick using the next larger key.

A BST is fast only if it is bushy. If you insert 1, 2, 3, 4, 5 in order, every node goes to the right, and the tree becomes a straight line. Then searching is as slow as scanning a list. Balanced trees, covered next, fix this.

Press Play on a diagram to walk through it one step at a time.

FlowDeleting a node
  1. 1
    Find node

    Walk left or right by comparison.

  2. 2
    No children

    Remove it.

  3. 3
    One child

    Replace node with its child.

  4. 4
    Two children

    Copy in-order successor value.

  5. 5
    Delete successor

    It has at most one child.

CompareSame keys, different insertion orders
Inserted 4, 2, 6, 1, 3, 5, 7
  • Root 4, perfectly balanced
  • Height 2
  • Search: at most 3 comparisons
  • O(log n) per operation
Inserted 1, 2, 3, 4, 5, 6, 7
  • Every node is a right child
  • Height 6
  • Search: up to 7 comparisons
  • O(n) per operation, like a list

In depth

Search and insert follow one path

Search compares the key with the current node and moves left or right. The work is one comparison per level, so the cost is O(h), where h is the height. Iterative search needs no stack at all: while node and node.val != key: node = node.left if key < node.val else node.right.

Insert walks the same path and attaches a new leaf where the search fell off. New keys always become leaves, so the tree's shape depends entirely on insertion order. Duplicates need a policy: ignore them, keep a count in the node, or always send equal keys to one side.

With n keys inserted in random order, the expected depth of a node is about 1.39 log2 n, and the expected height is also O(log n). But real data is often not random: sorted IDs, timestamps or alphabetical names produce a chain of height n - 1, where every operation is O(n).

  • Cost O(h) for search, insert and delete
  • Random insertion order: expected O(log n) height
  • Sorted insertion order: height n - 1

Deleting with zero, one or two children

First find the node. A leaf is simply removed: its parent's pointer becomes None. A node with one child is replaced by that child, which keeps the BST rule because the whole child subtree was already on the correct side of the parent.

A node with two children cannot just vanish. Replace its value with its in-order successor, the smallest key in its right subtree, found by going right once and then left as far as possible. The successor is larger than everything in the left subtree and smaller than everything else in the right subtree, so the rule still holds. Then delete the successor from the right subtree. The successor has no left child (otherwise that child would be smaller), so this second delete is an easy case.

Using the in-order predecessor (largest key in the left subtree) works equally well. Every case is O(h).

FlowDelete 50 (two children) from a BST
  1. 1
    Find 50

    It has left and right subtrees.

  2. 2
    Go right once

    To 70, the root of the right subtree.

  3. 3
    Go left to the end

    Reach 60: the successor.

  4. 4
    Copy

    Write 60 into the node that held 50.

  5. 5
    Remove old 60

    It had at most a right child: easy case.

Successor, predecessor and range queries

The in-order successor of node x is the next larger key. If x has a right child, it is the leftmost node of the right subtree. If not, it is the nearest ancestor for which x lies in the left subtree. Without parent pointers, find it from the root: walk down as in a search, and every time you go left, remember that node as a candidate; the last candidate is the successor.

This same idea answers floor and ceiling queries: the largest key <= x, or the smallest key >= x, in O(h). Python lists with bisect answer these too, but inserting into a list is O(n).

Range queries, such as all keys between 20 and 40, use a pruned in-order traversal: skip the left subtree when the node is below the range and the right subtree when it is above. The cost is O(h + k) for k results.

  • Successor with right child: leftmost of right subtree
  • Without: last ancestor where you went left
  • Range query: O(h + k)

Validating a BST correctly

The tempting check, left.val < node.val < right.val at every node, is wrong. Consider root 10 with left child 5, and 5 has a right child 15. Each parent-child pair looks fine, but 15 sits in the left subtree of 10, which breaks the rule.

The correct approach passes down bounds. The root may hold anything. Going left, the upper bound becomes the node's value; going right, the lower bound becomes the node's value. Every node must lie strictly within its bounds. This is O(n) time and O(h) space.

An equivalent check uses in-order traversal: a tree is a valid BST (with distinct keys) exactly when its in-order sequence is strictly increasing. Compare each visited value with the previous one, and stop at the first violation. Watch the duplicate policy: if equal keys are allowed on one side, use <= on that side only.

Learn it in 5 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Implement search and insert~40m
  2. 2
    Delete nodes with zero, one, two children~40m
  3. 3
    Find successor and predecessor~40m
  4. 4
    Validate a BST~40m
  5. 5
    Show degeneration into a linked list~40m

Key points

  • Search, insert and delete: O(h), which is O(log n) balanced and O(n) skewed.
  • In-order traversal visits keys in sorted order.
  • Validate a BST by passing down allowed min and max bounds.
  • Successor is the leftmost node of the right subtree.

Key terms

Tap a card to flip it. 0/3 known

Examples

python
def insert(node, key):            # O(h)
    if node is None:
        return TreeNode(key)
    if key < node.val:
        node.left = insert(node.left, key)
    elif key > node.val:
        node.right = insert(node.right, key)
    return node

def is_bst(node, lo=float('-inf'), hi=float('inf')):
    if node is None:
        return True
    return (lo < node.val < hi and is_bst(node.left, lo, node.val)
            and is_bst(node.right, node.val, hi))

Full delete with all three cases

This recursive delete returns the new root of each subtree, which keeps the parent links correct without tracking parents. Build the BST from [50, 30, 70, 20, 40, 60, 80], then delete 20 (a leaf), 30 (now one child, 40) and 50 (two children; its successor 60 moves up). The in-order traversal shows the remaining keys stay sorted.

python
def delete(node, key):
    if node is None: return None
    if key < node.val: node.left = delete(node.left, key)
    elif key > node.val: node.right = delete(node.right, key)
    else:
        if node.left is None: return node.right
        if node.right is None: return node.left
        s = node.right
        while s.left: s = s.left
        node.val = s.val
        node.right = delete(node.right, s.val)
    return node

root = None
for k in [50, 30, 70, 20, 40, 60, 80]: root = insert(root, k)
for k in [20, 30, 50]: root = delete(root, k)
print(inorder(root), root.val)  # [40, 60, 70, 80] 60

k-th smallest and range sum

In-order traversal of a BST visits keys in sorted order, so the k-th smallest is the k-th node visited. A generator lets us stop after k nodes, costing O(h + k). For a range sum between lo and hi, prune: if a node is below lo, only its right subtree can contribute; if above hi, only its left subtree.

python
def inorder_gen(n):
    if n:
        yield from inorder_gen(n.left)
        yield n.val
        yield from inorder_gen(n.right)

def kth_smallest(root, k):
    for i, v in enumerate(inorder_gen(root), 1):
        if i == k: return v

def range_sum(n, lo, hi):
    if n is None: return 0
    if n.val < lo: return range_sum(n.right, lo, hi)
    if n.val > hi: return range_sum(n.left, lo, hi)
    return n.val + range_sum(n.left, lo, hi) + range_sum(n.right, lo, hi)

Quick reference

  • BST rule: all keys in left subtree < node < all keys in right subtree
  • Search, insert, delete, min, max, successor: O(h)
  • Sorted insertion gives height n - 1; random insertion gives expected O(log n)
  • Two-child delete: copy the successor (leftmost of right subtree), then delete it
  • Validate with (lo, hi) bounds or a strictly increasing in-order sequence
  • Range query lo..hi: O(h + k) with pruning
  • Number of distinct BST shapes on n keys: the Catalan number C(n); 42 for n = 5

Common mistakes

  • Validating by comparing only with direct children instead of full bounds.
  • Assuming O(log n) without guaranteeing balance.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Root 10 has left child 5, and 5 has right child 15. Is it a valid BST?

Question 2

2When deleting a node with two children, why does its in-order successor have no left child?

Question 3

3You insert 1,000 sorted IDs into a plain BST. What is the cost of searching for the largest?

Question 4

4What does an in-order traversal of a valid BST with distinct keys produce?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write bst_min(root) and bst_max(root) iteratively. Example: for a BST built from [8, 3, 10, 1, 6, 14], min is 1 and max is 14.

  2. Exercise 2medium

    Write successor(root, x) that returns the smallest key greater than x in a BST without parent pointers, or None. x may or may not be in the tree. Example: for keys [8, 3, 10, 1, 6, 14], successor(root, 6) is 8.

  3. Exercise 3hard

    Write sorted_to_bst(a) that builds a height-balanced BST from a sorted list in O(n), then check its height is floor(log2 n) (in edges). Example: 7 keys give height 2.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Does Python have a built-in BST?
No. dict and set are hash tables with no ordering by key. For sorted containers, use bisect on a list for mostly-read data, or the third-party sortedcontainers package.
How should a BST handle duplicate keys?
Choose one policy and apply it everywhere: ignore duplicates, store a count in each node, or always send equal keys to the same side (for example right). Validation must match that policy.
Why learn plain BSTs if balanced trees exist?
Balanced trees are plain BSTs plus rebalancing. Search, successor, range queries and validation work exactly the same, so the plain version is the foundation.

Go deeper

ShareXLinkedInWhatsApp