Binary search tree

A binary tree where every left subtree holds smaller keys and every right subtree larger ones: O(log n) search, insert and ordered traversal when balanced.

Description

A binary search tree stores keys in nodes with up to two children, following one rule: everything in a node's left subtree is smaller, everything in its right subtree is larger. That rule makes searching a series of left-or-right decisions, like binary search on a structure that can grow.

To search, start at the root and go left if the key is smaller, right if larger, until you find it or fall off the tree. To insert, search for the key and attach a new node where the search ended. An in-order traversal (left subtree, node, right subtree) visits keys in sorted order.

Each step goes one level down, so the cost is the tree's height. For a well-shaped tree that's about log₂ n. But a plain BST doesn't control its shape: inserting keys in sorted order produces a chain, height n, and every operation becomes O(n). That's why production code uses balanced variants such as red-black or AVL trees.

BSTs support things hash tables can't: finding the minimum or maximum, the next larger key, and range queries such as all orders between two dates.

How it works

20304050607080

A BST. Searching for 60: right at 50, left at 70, found.

  1. 50 → 30, 70
  2. 30 → 20, 40
  3. 70 → 60, 80
  4. 20
  5. 40
  6. 60
  7. 80
A BST. Searching for 60: right at 50, left at 70, found.

Complexity

OperationAverageWorst
SearchThe worst case is a tree degenerated into a chain.O(log n)O(n)
InsertO(log n)O(n)
DeleteO(log n)O(n)
Min, max, next largerO(log n)O(n)
In-order traversalO(n)O(n)

Space: O(n)

Balanced trees guarantee the O(log n) average as a worst case. A plain BST is mainly a teaching tool and the foundation for those variants.

TypeScript implementation

A binary search tree with insert, search, in-order traversal and a range query, plus a demonstration of how sorted input makes it degenerate.

binary-search-tree.ts
// A binary search tree: smaller keys to the left, larger to the right.

class TreeNode {
  key: number;
  left: TreeNode | null = null;
  right: TreeNode | null = null;
  constructor(key: number) {
    this.key = key;
  }
}

export class BST {
  root: TreeNode | null = null;

  insert(key: number): void {
    const node = new TreeNode(key);
    if (!this.root) {
      this.root = node;
      return;
    }
    let cur = this.root;
    for (;;) {
      if (key < cur.key) {
        if (!cur.left) return void (cur.left = node);
        cur = cur.left;
      } else {
        if (!cur.right) return void (cur.right = node);
        cur = cur.right;
      }
    }
  }

  /** Returns the number of nodes visited, or -1 if not found. */
  search(key: number): number {
    let cur = this.root, steps = 0;
    while (cur) {
      steps++;
      if (key === cur.key) return steps;
      cur = key < cur.key ? cur.left : cur.right;
    }
    return -1;
  }

  /** All keys in [lo, hi], in order, skipping subtrees that can't contain any. */
  range(lo: number, hi: number, node = this.root, out: number[] = []): number[] {
    if (!node) return out;
    if (lo < node.key) this.range(lo, hi, node.left, out);
    if (lo <= node.key && node.key <= hi) out.push(node.key);
    if (hi > node.key) this.range(lo, hi, node.right, out);
    return out;
  }

  height(node = this.root): number {
    // iterative level count, so a degenerate tree doesn't overflow the stack
    let level = node ? [node] : [], h = 0;
    while (level.length) {
      h++;
      level = level.flatMap((n) => [n.left, n.right].filter((c): c is TreeNode => c !== null));
    }
    return h;
  }
}

export function demo(): string[] {
  const t = new BST();
  for (const k of [50, 30, 70, 20, 40, 60, 80]) t.insert(k);
  const lines = [
    `search 60: found after ${t.search(60)} steps; search 65: ${t.search(65)}`,
    `keys between 35 and 65: ${t.range(35, 65).join(", ")}`,
    `height with 7 keys in good order: ${t.height()}`,
  ];
  const chain = new BST();
  for (let k = 1; k <= 1000; k++) chain.insert(k); // sorted input
  lines.push(`height after inserting 1..1000 in order: ${chain.height()} (a chain; balanced would be 10)`);
  return lines;
}

When to use it

Use it when

  • You need keys in order: sorted iteration, minimum and maximum, predecessor and successor.
  • Range queries: all keys between two values.
  • Learning, or when inputs are random enough that the tree stays reasonably balanced.

Avoid it when

  • Inputs may arrive sorted or nearly sorted: use a balanced search tree.
  • You only need exact lookups: a hash table is faster.
  • The data is static: a sorted array with binary search is simpler and more compact.

Pitfalls

  • Degenerating into a linked list with sorted inserts.
  • Deleting a node with two children incorrectly. Replace it with its in-order successor (the smallest key in its right subtree), then delete that.
  • Duplicate keys without a clear rule for which side they go on.
  • Recursion depth on degenerate trees, which can overflow the stack.

Alternatives

Balanced search tree

Choose it when you need guaranteed O(log n), which in practice is always.

Hash table

Choose it when order doesn't matter and you only look up exact keys.

Binary heap

Choose it when you only need the minimum or maximum, not full ordering.