Lazy In-Order Iterator Over a Binary Search Tree
Last updated: November 29, 2026
Quick Overview
Implement an iterator over a binary search tree that returns keys in ascending order with `next()` and `has_next()`, using O(h) memory where h is the tree height rather than storing all keys.
Microsoft
November 29, 20260
0
0 solved
Implement an iterator over a binary search tree that returns keys in ascending order with `next()` and `has_next()`, using O(h) memory where h is the tree height rather than storing all keys.
Microsoft technical screens use this to test controlled traversal with an explicit stack, a pattern that shows up in index scans for products like SQL Server. The interviewer checks O(h) memory and amortized O(1) per call.
What the Interviewer Expects
- Simulate recursive in-order traversal with an explicit stack
- Push the left spine on construction and after each pop's right child
- Argue amortized O(1) per next call
- Keep memory at O(h)
- Handle an empty tree and a skewed tree
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Add a peek() method.
- Support seek(key) to start from the first key at least key.
- How would you iterate in descending order, or both directions?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Constructor takes the root of a BST (possibly None).
next()returns the next smallest key;has_next()reports whether one remains.- Memory O(h);
nextamortized O(1)....
High-Level Design
Recursive in-order traversal visits left subtree, node, right subtree. The call stack at any moment holds the path of nodes whose left subtree is being visited. We keep that path explicitly.
On const...