Binary Search Tree Iterator II - 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() - Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.

int next() - Moves the pointer to the right, then returns the number at the pointer.

boolean hasPrev() - Returns true if there exists a number in the traversal to the left of the pointer, otherwise returns false.

int prev() - Moves the pointer to the left, then returns the number at the pointer.

Notice: 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() and prev() calls will always be valid.

Input & Output

Example 1 — Basic Iterator Operations
$ Input: commands = ["BSTIterator", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"], inputs = [[[7,3,15,null,null,9,20]], [], [], [], [], [], [], [], [], []]
Output: [null, true, 3, true, 7, true, 9, true, 7]
💡 Note: Initialize iterator with BST [7,3,15,null,null,9,20]. In-order traversal: 3,7,9,15,20. Iterator starts before first element, so first next() returns 3, then 7, then 9. At this point hasPrev() returns true since we can go back, and prev() returns 7.
Example 2 — Bidirectional Navigation
$ Input: commands = ["BSTIterator", "next", "next", "hasPrev", "prev", "hasNext", "next"], inputs = [[[7,3,15,null,null,9,20]], [], [], [], [], [], []]
Output: [null, 3, 7, true, 3, true, 7]
💡 Note: After next() twice (3,7), hasPrev() is true. prev() goes back to 3, then next() moves forward to 7 again.
Example 3 — Edge Case with Single Node
$ Input: commands = ["BSTIterator", "hasNext", "next", "hasPrev", "hasNext"], inputs = [[[5]], [], [], [], []]
Output: [null, true, 5, false, false]
💡 Note: Single node BST. hasNext() is true initially, next() returns 5. After consuming the only element, hasPrev() is false (started before first element) and hasNext() is false.

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, next, hasPrev, and prev

Visualization

Tap to expand
Binary Search Tree Iterator II INPUT Binary Search Tree 7 3 15 9 20 In-order: 3, 7, 9, 15, 20 Commands: BSTIterator, hasNext, next, hasNext, next, hasNext, next, hasNext, next, hasNext Pointer starts before all elements ALGORITHM STEPS 1 Initialize Iterator Store tree root, index = -1 visited[] tracks traversed nodes 2 next() Operation If index+1 in visited: return it Else: do in-order step, cache 3 prev() Operation Decrement index, return visited[index] from cache 4 hasNext/hasPrev hasNext: more in cache or tree hasPrev: index > 0 Data Structures Stack (for traversal): 7 15 visited[] cache: 3 7 9 15 ... idx FINAL RESULT Operation Results Command Output BSTIterator null hasNext() true next() 3 hasNext() true next() 7 hasNext() true next() 9 hasNext() true next() 15 hasNext() true Output Array: [null,true,3,true,7,true,9,true,15,true] Time: O(1) avg | Space: O(n) Bidirectional traversal: OK Key Insight: Cache visited nodes in an array to enable O(1) backward movement (prev). Use lazy in-order traversal with a stack for forward movement (next). The index pointer tracks current position in the cached array, enabling bidirectional iteration without re-traversing the tree. TutorialsPoint - Binary Search Tree Iterator II | Optimal Solution
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
32.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen