4. Linked Lists, Trees & Heaps

Binary Search Trees (BST) & Priority Queues (heapq)

Validate Binary Search Trees using min/max bounds and solve Top-K / streaming median / task scheduling problems in O(n log k) using Python's heapq min-heap.

6 min readUpdated 2026-11-30
In This Lesson
  • Validate BST ordering globally using lower/upper bounds rather than immediate child checks
  • Use Python's heapq min-heap for O(log n) push/pop and O(1) peek
  • Simulate a max-heap cleanly in Python by negating numeric priorities

Two ordered structures dominate priority scheduling and fast range lookups in technical interviews: Binary Search Trees (BSTs) and Priority Queues (heapq).

Why It Matters: Maintaining Order Dynamically

Suppose new scores arrive in a live stream and you repeatedly need the current Top-k largest scores (or the next highest-priority job):

  • Re-sorting on every arrival: Calling sorted(items) after each of n insertions costs n × O(n log n) → O(n² log n)!
  • A Binary Heap (heapq): Keeps only the smallest (or largest) element at index 0 in O(1) and inserts/removes in O(log n), solving Top-k over n items in O(n log k) time and O(k) space!

Pattern 1: Binary Search Trees (Watch the Global Bounds Trap!)

In a valid BST, every node in node.left's entire subtree must be strictly < node.val, and every node in node.right's entire subtree must be strictly > node.val.

python
def is_valid_bst(node, low=float("-inf"), high=float("inf")) -> bool:
    if not node:
        return True
    if not (low < node.val < high):
        return False
    return is_valid_bst(node.left, low, node.val) and is_valid_bst(node.right, node.val, high)

Dry-Run Trace: Why Local Checks Fail on [5, 1, 6, 4, 8]

Consider root 5, left child 1, right child 6 with children (4, 8):

  • Local check at 6: 4 < 6 < 8 looks valid!
  • Global bounds check:
    1. is_valid_bst(5, -inf, +inf) → True, passes (5, +inf) to right child 6.
    2. is_valid_bst(6, 5, +inf) → 5 < 6 < +inf is True, passes (5, 6) to left child 4.
    3. is_valid_bst(4, 5, 6) → 5 < 4 < 6 is False! Caught immediately because 4 sits in the right subtree of 5!

Pattern 2: Priority Queues with heapq

Size-K Min-Heap for O(n log k) Top-K Largest

Push 6 into [4, 5]

[4, 5, 6] (len > 2)

heappop() evicts 4 → [5, 6]

heap[0] == 5 (2nd largest!)

Keep a min-heap capped at size k=2: whenever a larger item enters, heappop() evicts the smallest so heap[0] always holds the K-th largest!

Python's built-in heapq module turns a standard list into a min-heap (smallest element always sits at h[0]):

OperationCodeTime Complexity
Build heap from existing listheapq.heapify(nums)O(n) (faster than n pushes!)
Push elementheapq.heappush(h, x)O(log n)
Pop smallest elementheapq.heappop(h)O(log n)
Peek smallest elementh[0]O(1)
Top-k largest in streamMin-heap capped at size kO(n log k) time, O(k) space

Step-by-Step Dry-Run: kth_largest([3, 2, 1, 5, 6, 4], k=2)

To find the 2nd largest, keep a min-heap of size 2—whenever size exceeds 2, heappop evicts the smallest so the 2 largest survivors remain!

Incoming xHeap After heappushlen > 2?Evicted (heappop)Heap After Step
3[3]No—[3]
2[2, 3]No—[2, 3]
1[1, 3, 2]Yes1[2, 3]
5[2, 3, 5]Yes2[3, 5]
6[3, 5, 6]Yes3[5, 6]
4[4, 6, 5]Yes4[5, 6]

At the end, min_heap[0] is 5—the exact 2nd largest element!

Edge Cases & Python Tuple Comparison Traps

  • Empty heap: Calling heapq.heappop([]) or reading h[0] raises IndexError—always check if h:.
  • Simulating a Max-Heap: Push -val and negate back on pop (-heapq.heappop(h)).
  • Tuple ties in heapq: When pushing (priority, node_obj), if two items have equal priority, Python tries to compare node_obj < node_obj and crashes with TypeError: '<' not supported between instances of 'Node' and 'Node'! Fix it by pushing a tie-breaker counter: (priority, tie_id, node_obj).
Do Not Confuse heapq[1] or Sorted Order with a Heap

A heap only guarantees h[0] is the smallest element—h itself is NOT sorted! Never index h[-1] expecting the largest element or iterate for x in h: expecting sorted order. Pop repeatedly with heappop(h) when you need sorted output.

Use heapq.heapify(arr) Instead of Pushing One by One

If all n items are already in a list, heapq.heapify(arr) rearranges the list in place in O(n) time using bottom-up sift-down, compared to O(n log n) for n individual heappush calls.

Try It Yourself in the Playground

Test is_valid_bst, kth_largest (min-heap of size k), and a Max-Heap Task Scheduler below:

Python 3Try It Live: BST Validation & heapq Top-K
Output

Click “Run Code” to execute this snippet right in your browser.

Mini-Challenge: How do you use Python's heapq (which is a min-heap) to behave as a max-heap for task priorities?

Quick Checkpoints

Check Your Understanding

Why is checking only node.left.val < node.val < node.right.val insufficient to validate a Binary Search Tree?

Check Your Understanding

What is the time complexity of finding the K-th largest element in a stream of n numbers using a min-heap capped at size k?

Check Your Understanding

You build a heap from an existing list of n elements using heapq.heapify(arr). What is the time complexity?