Command Palette

Search for a command to run...

Module 17

Binary Search Trees

Ordered trees: search and insert in O(h), validate with ranges, sorted order from in-order walks, and Java's TreeMap.

Intermediate 3 lessons 9 problems ~40 min of lessons

A binary search tree keeps one rule at every node: everything in the left subtree is smaller, everything in the right subtree is larger. That single rule lets you discard a whole subtree at each step, which is binary search on a tree, and it makes an in-order walk produce the values in sorted order.

This module covers search, insert and delete, validating the rule correctly (it's about ranges, not just parent and child), in-order tricks like the k-th smallest value, and the balanced BSTs you use every day through Java's TreeMap and TreeSet.

Best after: Binary Trees

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. Following one path down the tree using the ordering.

  2. Insert = search until you fall off, then attach a leaf.

  3. Passing an allowed range down the tree.

  4. In-order is sorted, so count as you walk and stop at k.

  5. The ordering tells you where the split happens without searching subtrees.

  6. Building a balanced tree: the middle element is the root, and each half becomes a subtree.

  7. Reusing array patterns on a tree: in-order gives a sorted list for two pointers, or a hash set during any traversal.

  8. The three deletion cases, with the in-order successor for nodes that have two children.

  9. Pausing an in-order traversal: keep the stack between calls so each next() is amortised O(1).