Binary Search Tree Iterator - Problem
Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):
BSTIterator(TreeNode root)Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.boolean hasNext()Returnstrueif there exists a number in the traversal to the right of the pointer, otherwise returnsfalse.int next()Moves the pointer to the right, then returns the number at the pointer.
Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.
You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.
Input & Output
Example 1 — Basic BST Iterator
$
Input:
commands = ["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"], values = [[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
›
Output:
[null, 3, 7, true, 9, true, 15, true, 20, false]
💡 Note:
Initialize iterator with BST root 7. In-order traversal gives 3,7,9,15,20. Each next() returns the next smallest value, hasNext() checks if more values exist.
Example 2 — Single Node Tree
$
Input:
commands = ["BSTIterator", "next", "hasNext"], values = [[[5]], [], []]
›
Output:
[null, 5, false]
💡 Note:
Tree with single node 5. First next() returns 5, then hasNext() returns false as no more values exist.
Example 3 — Left Skewed Tree
$
Input:
commands = ["BSTIterator", "next", "next", "hasNext"], values = [[[3, 1, null, null, 2]], [], [], []]
›
Output:
[null, 1, 2, true]
💡 Note:
Left-skewed BST. In-order traversal: 1,2,3. After getting 1 and 2, hasNext() is true because 3 remains.
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
Visualization
Tap to expand
Understanding the Visualization
1
Input BST
Binary search tree [7,3,15,null,null,9,20]
2
In-order Sequence
Values in sorted order: 3,7,9,15,20
3
Iterator Operations
next() and hasNext() return values on-demand
Key Takeaway
🎯 Key Insight: Use a stack to simulate recursive traversal, generating sorted values on-demand with minimal memory
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code