Skip to the content.

8. Binary Search Trees

Back to the index

A binary tree where every left descendant is smaller and every right descendant is larger (or equal). Search, insert and delete follow one root-to-leaf path: O(log n) if balanced, O(n) if not.

How it works

The BST rule lets each comparison discard a whole subtree, just like binary search on a sorted array. To search, start at the root and go left when the target is smaller, right when larger. To insert, search for the value and attach a new node where the search falls off the tree.

The shape depends on insertion order. Inserting sorted data produces a linked list with O(n) operations, which is why production systems use self-balancing trees (red-black, AVL, B-trees).

Diagram

graph TD
    n_8["8"]
    n_8 -->|L| n_3
    n_8 -->|R| n_10
    n_10["10"]
    n_10 -->|R| n_14
    n_14["14"]
    n_14 -->|L| n_13
    n_13["13"]
    n_3["3"]
    n_3 -->|L| n_1
    n_3 -->|R| n_6
    n_6["6"]
    n_6 -->|L| n_4
    n_6 -->|R| n_7
    n_7["7"]
    n_4["4"]
    n_1["1"]

Step-by-step trace

Input: Insert [8, 3, 10, 1, 6, 14, 4, 7, 13], then search for 7 and 5.

Operation Nodes compared (root -> down) Result
insert 8 (empty tree) becomes the root
insert 3 8 placed as left child of 8
insert 10 8 placed as right child of 8
insert 1 8 -> 3 placed as left child of 3
insert 6 8 -> 3 placed as right child of 3
insert 14 8 -> 10 placed as right child of 10
insert 4 8 -> 3 -> 6 placed as left child of 6
insert 7 8 -> 3 -> 6 placed as right child of 6
insert 13 8 -> 10 -> 14 placed as left child of 14
search 7 8 -> 3 -> 6 -> 7 found
search 5 8 -> 3 -> 6 -> 4 not found (fell off the tree)

Result: Inorder traversal gives sorted order: [1, 3, 4, 6, 7, 8, 10, 13, 14].

Complexity

Operation Time Space
Search / insert / delete (balanced) O(log n) O(1) iterative
Search / insert / delete (degenerate) O(n) O(1) iterative
Inorder traversal (sorted output) O(n) O(h)

Python reference implementation

class BST:
    def __init__(self):
        self.root = None

    def insert(self, val):
        if self.root is None:
            self.root = TreeNode(val)
            return
        node = self.root
        while True:
            if val < node.val:
                if node.left is None:
                    node.left = TreeNode(val)
                    return
                node = node.left
            else:
                if node.right is None:
                    node.right = TreeNode(val)
                    return
                node = node.right

    def contains(self, val):
        node = self.root
        while node:
            if val == node.val:
                return True
            node = node.left if val < node.val else node.right
        return False

Common mistakes and tips


The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.

Previous: Binary Trees and Traversals Next: Heaps and Priority Queues