#173

Binary Search Tree Iterator

Medium Controlled inorder with a stack

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Build an iterator over a BST that returns values in increasing order with next() and hasNext(), using O(h) memory.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: return values in sorted order one at a time using O(h) memory.

Why this works: keep only the left spine on a stack (a paused inorder traversal); after popping a node, push the left spine of its right child.

Example: 7 (3, 15 (9, 20))

stack [7, 3] → next 3next 7 → push 15, 9 → next 9, 15, 20

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Flattening the whole tree into a list in the constructor — O(n) memory.

Solve on LeetCode ↗
Complexity
  • Time: Amortised O(1) per next().
  • Space: O(h).
Topic: Binary Search Trees
🎬 Episodes 61–63: video coming soon