Skip to main content
Intermediate ~15 min read

Binary Search Trees

Order inside a tree: left < node < right. Search, insert, delete in O(log n), and what unbalanced trees do to that promise.

Prerequisites: Binary Search, Binary Trees & Traversals

A binary search tree imposes one invariant everywhere: for EVERY node, all values in its left subtree are smaller, and all values in its right subtree are larger. That local rule creates global order, which lets you binary-search the tree. At each node, one comparison tells you which subtree can hold the target; the other is discarded entirely, exactly like discarding half an array.

Search, insert, and delete all follow the same path shape: walk from the root, one comparison per level. Cost = height + 1. For a balanced tree that's O(log n). But the invariant says nothing about BALANCE, insert sorted data 1,2,3,4,5 into a naive BST and you get a linked list in disguise, O(n) for everything. Self-balancing trees (AVL, red-black) add rotation rules that keep height ≈ log n; they power Java's TreeMap and the C++ std::map.

Search and insert

bst.js
class BSTNode {
  constructor(value) { this.value = value; this.left = null; this.right = null; }
}

function insert(root, value) {
  if (!root) return new BSTNode(value);          // found the empty slot
  if (value < root.value) root.left = insert(root.left, value);
  else if (value > root.value) root.right = insert(root.right, value);
  return root;                                    // equal → ignore (set semantics)
}

function search(root, value) {
  let cur = root;
  while (cur) {
    if (value === cur.value) return true;
    cur = value < cur.value ? cur.left : cur.right;   // discard one subtree
  }
  return false;
}

// In-order traversal of a BST yields values in SORTED order,
// the invariant's most elegant consequence:
function sortedValues(root, out = []) {
  if (!root) return out;
  sortedValues(root.left, out);
  out.push(root.value);
  sortedValues(root.right, out);
  return out;
}
Operation / caseCostNotes
Search / insert / delete (balanced)O(log n)height ≈ log₂ n
Search / insert / delete (degenerate)O(n)sorted insertion order
In-order traversalO(n)returns sorted sequence
Range queriesO(log n + k)k = results, where BSTs beat hash tables

Check your understanding

  1. 1.The BST invariant is checked:
  2. 2.Inserting [10, 5, 15, 2, 7] then running in-order traversal outputs:
  3. 3.When is a hash map the better choice over a BST?

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Keep going