How do you implement a BST iterator that returns the next smallest key in average O(1) time?
PICTURE THIS: STACK VS QUEUE
Simple meaning
Push the left spine onto a stack.
WHY — BST instead of guessing?
Why interviewers care about BST:
question about BST.
trade-offs, and what you would actually do on a DSA project - not buzzwords.
Name the idea, why it exists, then one short example.
End with when you use it and one common pitfall.
STEPS — What happens step by step?
Before you speak the answer, walk the interviewer through these steps:
- 1Push the left spine
onto a stack.
- 2next pops a node
and pushes the left spine of its right child.
- 3How it works
Space is O(h)
- 4next and hasNext are
amortized O(1) because each node is pushed and popped once across n calls.
- 5Flattening all keys up
front is O(n) space.
- 6Close
When you pick this over the alternative.
EXAMPLE — See it in action
Here's a short line you can speak, broken into clear beats:
Note: Adapt this scaffold to your own project — keep it under 60–90 seconds.
Key takeaway
Push the left spine onto a stack. next pops a node and pushes the left spine of its right child.