Binary Search Tree Iterator - Problem
Binary Search Tree Iterator
Design and implement an iterator that traverses a Binary Search Tree (BST) in sorted order. Your iterator should behave like a "cursor" that moves through the tree's elements from smallest to largest.
What you need to implement:
Key Requirements:
• The iterator should traverse in in-order (sorted) sequence
•
• Use O(h) memory at most, where h is the height of the tree
Example: For BST [7, 3, 15, null, null, 9, 20], the iterator should return: 3, 7, 9, 15, 20
Design and implement an iterator that traverses a Binary Search Tree (BST) in sorted order. Your iterator should behave like a "cursor" that moves through the tree's elements from smallest to largest.
What you need to implement:
BSTIterator(TreeNode root)- Initialize the iterator with the BST's rootnext()- Return the next smallest number in the BSThasNext()- Check if there are more elements to iterate
Key Requirements:
• The iterator should traverse in in-order (sorted) sequence
•
next() and hasNext() should run in average O(1) time• Use O(h) memory at most, where h is the height of the tree
Example: For BST [7, 3, 15, null, null, 9, 20], the iterator should return: 3, 7, 9, 15, 20
Input & Output
example_1.py — Basic BST Iterator
$
Input:
BSTIterator iterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);
iterator.next(); // return 3
iterator.next(); // return 7
iterator.hasNext(); // return True
iterator.next(); // return 9
iterator.hasNext(); // return True
iterator.next(); // return 15
iterator.next(); // return 20
iterator.hasNext(); // return False
›
Output:
3, 7, True, 9, True, 15, 20, False
💡 Note:
The BST has nodes [3, 7, 9, 15, 20] in sorted order. The iterator returns them one by one and correctly indicates when no more elements exist.
example_2.py — Single Node BST
$
Input:
BSTIterator iterator = new BSTIterator([42]);
iterator.hasNext(); // return True
iterator.next(); // return 42
iterator.hasNext(); // return False
›
Output:
True, 42, False
💡 Note:
For a single-node BST, hasNext() initially returns true, next() returns the only value, then hasNext() returns false.
example_3.py — Left-Skewed BST
$
Input:
BSTIterator iterator = new BSTIterator([3, 1, null, null, 2]);
iterator.next(); // return 1
iterator.next(); // return 2
iterator.next(); // return 3
iterator.hasNext(); // return False
›
Output:
1, 2, 3, False
💡 Note:
Even for unbalanced trees, the iterator maintains in-order traversal sequence correctly.
Visualization
Tap to expand
Understanding the Visualization
1
Setup Bookmarks
Place bookmarks on all shelves along the leftmost path - these represent the stack initialization with left-spine nodes.
2
Read Next Book
Take the bottommost bookmark (stack top), read that book, and if that shelf has books to the right, bookmark the leftmost path of those books.
3
Continue Reading
Repeat the process - each book is accessed exactly once, and bookmarks efficiently guide us to the next book in alphabetical order.
Key Takeaway
🎯 Key Insight: By maintaining only the left-spine path in our stack, we achieve the perfect balance of time and space efficiency. Each node is processed exactly once, giving us amortized O(1) operations while using minimal O(h) space - just like keeping smart bookmarks instead of reorganizing an entire library!
Time & Space Complexity
Time Complexity
O(1)
Amortized O(1) for next() and O(1) for hasNext(). Each node visited exactly once across all operations.
✓ Linear Growth
Space Complexity
O(h)
Stack stores at most h nodes where h is height of tree (left-spine path)
✓ Linear Space
Constraints
- The number of nodes in the tree is in the range [1, 105]
- 0 ≤ Node.val ≤ 106
- At most 105 calls will be made to hasNext and next
-
Follow-up: Could you implement
next()andhasNext()to run in average O(1) time and use O(h) memory, where h is the height of the tree?
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code