Binary Search Trees and Heaps

Lesson 15 of 20

Watch 47 and 12 walk the compare path into a BST, then see 9 sift to the root of a min-heap — PriorityQueue included.

The big picture

Why ordered trees

Two structures promise order without sorting: the BST keeps values navigable, the heap keeps the minimum on tap. Both are just binary trees with a rule.

The BST rule

Every node obeys left < node < right. One invariant, and inorder traversal prints the whole tree sorted.

Insert = a search that lands

Walk down comparing; the first null slot is the new home. Cost is O(h) — the height, not n.

Balance is money

Balanced height ≈ log₂ n: a million keys need about 20 levels. A skewed BST collapses into a linked list.

Heaps live in arrays

Children of index i sit at 2i + 1 and 2i + 2; the parent is (i − 1) / 2. No pointers needed at all.

Java ships both

TreeMap is a balanced BST under the hood; PriorityQueue is a min-heap — poll() always returns the smallest.