The "Binary Search Tree Iterator interview question" is a design challenge. You are given the root of a Binary Search Tree (BST) and you need to implement an iterator that returns the values of the tree in in-order (sorted) sequence. The iterator must support two methods: next() (returns the next smallest number) and hasNext() (returns true if a next number exists).
Companies like Meta, Amazon, and LinkedIn use the "Binary Search Tree Iterator coding problem" to test a candidate's knowledge of Tree Traversal and State Management. Unlike a simple recursive traversal, an iterator must "pause" and "resume" its progress. It requires you to simulate the call stack using a real stack data structure.
This problem uses the Stack-based In-order Traversal pattern.
next():
hasNext(): Simply check if the stack is empty.BST: 7 is root, 3 is left child, 15 is right child. 15 has 9 (left) and 20 (right).
[7, 3].next(): Pop 3. Stack = [7]. Return 3.next(): Pop 7. 7 has a right child (15).
[15, 9]. Return 7.next(): Pop 9. Stack = [15]. Return 9.next(): Pop 15. 15 has a right child (20). Stack = [20]. Return 15.next() method.Iterative tree traversal is a common "Design interview pattern." If you can explain why a stack is used to replace recursion, you show a strong understanding of how the computer manages function calls. Practice this alongside "Iterative DFS" and "BFS."
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Binary Search Tree Iterator II | Medium | Solve | |
| Increasing Order Search Tree | Easy | Solve | |
| Delete Node in a BST | Medium | Solve | |
| Construct Binary Search Tree from Preorder Traversal | Medium | Solve | |
| Insert into a Binary Search Tree | Medium | Solve |