Binary Search Trees and Heaps

Lesson 15 of 20

Watch inserts compare their way down a BST — then a new minimum sift all the way to the top of a min-heap.

The big picture

The big picture

Two trees, two promises. A BST promises total order — smaller left, larger right. A heap promises only that parents beat children — and buys O(1) minimums with it.

The BST rule

At every node: smaller values live in the left subtree, larger in the right. One comparison per level picks the direction.

Search cost = height

A balanced BST with 1,000,000 nodes is about 20 levels deep — 20 comparisons find any value, insert any value.

Inserts land at leaves

A new key walks a root-to-leaf compare path and attaches to the first empty slot. Nothing ever shifts or moves.

The heap trade

A min-heap only promises parent ≤ children. The minimum is always at the root (O(1)), but hunting an arbitrary value costs O(n).

Heaps live in arrays

Children of index i sit at 2i+1 and 2i+2; the parent is (i-1)/2. No pointers, no allocations — completeness makes the math work.

STL gives you both

std::map is a balanced BST under the hood; std::priority_queue is a heap — a max-heap unless you flip the comparator.