Binary Search Tree Iterator II - Problem

Design a bidirectional iterator for a Binary Search Tree (BST) that can traverse both forward and backward through the tree's in-order sequence.

You need to implement the BSTIterator class with the following methods:

  • BSTIterator(TreeNode root): Initialize the iterator. The pointer starts at a position before the smallest element.
  • boolean hasNext(): Returns true if there's a next element in the forward direction.
  • int next(): Moves the pointer forward and returns the current element.
  • boolean hasPrev(): Returns true if there's a previous element in the backward direction.
  • int prev(): Moves the pointer backward and returns the current element.

Key Points:

  • The iterator traverses the BST in in-order sequence (left โ†’ root โ†’ right)
  • Initial position is before the smallest element, so first next() returns the minimum value
  • You can assume all calls to next() and prev() are valid

Example: For BST [7,3,15,null,null,9,20], the in-order sequence is [3,7,9,15,20]

Input & Output

example_1.py โ€” Basic BST Iterator
$ Input: root = [7,3,15,null,null,9,20] Operations: ["BSTIterator","next","next","hasNext","next","hasNext","next","next","hasNext"]
โ€บ Output: [null,3,7,true,9,true,15,20,false]
๐Ÿ’ก Note: Initialize iterator with BST. The in-order sequence is [3,7,9,15,20]. Start before 3, then next() calls return 3,7,9,15,20 in sequence.
example_2.py โ€” Bidirectional Movement
$ Input: root = [7,3,15,null,null,9,20] Operations: ["BSTIterator","next","next","prev","next","next"]
โ€บ Output: [null,3,7,3,7,9]
๐Ÿ’ก Note: After getting 3,7 with next(), prev() goes back to 3. Then next() returns 7,9. Shows bidirectional capability.
example_3.py โ€” Edge Cases
$ Input: root = [1] Operations: ["BSTIterator","hasNext","next","hasNext","hasPrev","prev","hasPrev"]
โ€บ Output: [null,true,1,false,true,1,false]
๐Ÿ’ก Note: Single node tree. hasNext() is true initially, next() returns 1, then hasNext() false. Can go back with prev().

Visualization

Tap to expand
BST Iterator: Two-Stack Visualization7315920Next Stack73Forward traversalPrev Stack(initially empty)Backward traversal
Understanding the Visualization
1
Initialize Bookmarks
Set up two bookmark stacks - one for 'pages to read forward' and one for 'pages already read'
2
Forward Navigation
Move current page to 'read' stack, add new reachable pages to 'forward' stack
3
Backward Navigation
Move current page back to 'forward' stack, add reachable pages to 'read' stack
4
State Management
Each operation maintains the correct state for both directions efficiently
Key Takeaway
๐ŸŽฏ Key Insight: Two stacks simulate the recursive call stack of in-order traversal, providing O(1) amortized operations with optimal O(h) space usage.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(1) amortized per operation

Each node is pushed and popped at most twice across all operations

n
2n
โœ“ Linear Growth
Space Complexity
O(h)

Two stacks storing at most h nodes each where h is tree height

n
2n
โœ“ 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, next, hasPrev, and prev
  • All calls to next() and prev() are guaranteed to be valid
Asked in
Google 45 Microsoft 38 Amazon 32 Meta 28
23.6K Views
Medium-High Frequency
~25 min Avg. Time
892 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