Binary Search Trees and Heaps

Lesson 15 of 20

Follow 40 down a BST comparing at every level, then watch heapq heapify a jumbled list and pop the minimum for free.

The big picture

Two ordered cousins

Both structures put their keys in order — but a BST spreads them out for searching, while a heap crowds the minimum at the very top.

The BST rule

At every node: everything in the left subtree is smaller, everything right is bigger. One rule, applied recursively.

Search = descend

Compare and go left or right. A balanced 1,000-key BST finds any key in about 10 comparisons — one per level.

Insert = same walk

Follow the compares until you hit an empty slot, then link the new node in. Nothing else ever moves.

Heap = tree in a list

A complete binary tree stored flat in an array: children of slot i live at 2i+1 and 2i+2, the parent at (i-1)//2.

The heap deal

heap[0] is always the minimum. heapify costs O(n); push and pop cost O(log n) — priority-queue fuel.

heapq built in

Python ships heapq: heapify, heappush and heappop work on a plain list. One import, zero classes.