← All coursesDSA Foundations

Lesson 12 of 19

Binary search trees

Each node is a fork. Smaller keys belong in its left subtree and larger keys in its right. One comparison tells you which branch to follow.

The shape of a tree determines the search cost

A binary search tree keeps smaller keys in the left subtree and larger keys in the right subtree, assuming distinct keys. A search follows one path from the root. An ordinary tree can grow tall if keys arrive in sorted order. A balanced shape keeps that path short.

Work through an example

Insert 1, 2, 3 into an empty binary search tree without rebalancing. How many comparisons find 3? What if you insert 2, 1, 3?

Step-by-step solution
  1. With 1 first, 2 becomes its right child and 3 becomes the right child of 2. Search visits 1, 2 and 3.
  2. With 2 first, 1 goes left and 3 goes right. Search visits 2 and then 3.
  3. The keys are identical in both trees. Their shapes explain the difference between three comparisons and two.
JavaScript example
const leaf = key => ({ key, left: null, right: null });
const root = { key: 2, left: leaf(1), right: leaf(3) };
function pathTo(node, target) {
  const path = [];
  while (node) {
    path.push(node.key);
    if (node.key === target) break;
    node = target < node.key ? node.left : node.right;
  }
  return path;
}
pathTo(root, 3); // [2, 3]
DSA compiler

Try it yourself

Finish the animation to unlock this question.

At root 8 you want 6. At its left child 4, which way now?

Related exercise · Validate a binary search tree · Take the end-of-stage challenge