Binary Search Tree Iterator II Problem
Description
LeetCode Problem 1586.
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 theBSTIteratorclass. Therootof 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.boolean hasPrev()Returnstrueif there exists a number in the traversal to the left of the pointer, otherwise returnsfalse.int prev()Moves the pointer to the left, 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() and prev() calls will always be valid. That is, there will be at least a next/previous number in the in-order traversal when next()/prev() is called.
Example 1:

Input
["BSTIterator", "next", "next", "prev", "next", "hasNext", "next", "next", "next", "hasNext", "hasPrev", "prev", "prev"]
[[[7, 3, 15, null, null, 9, 20]], [null], [null], [null], [null], [null], [null], [null], [null], [null], [null], [null], [null]]
Output
[null, 3, 7, 3, 7, true, 9, 15, 20, false, true, 15, 9]
Explanation
// The underlined element is where the pointer currently is.
BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]); // state is [3, 7, 9, 15, 20]
bSTIterator.next(); // state becomes [3, 7, 9, 15, 20], return 3
bSTIterator.next(); // state becomes [3, 7, 9, 15, 20], return 7
bSTIterator.prev(); // state becomes [3, 7, 9, 15, 20], return 3
bSTIterator.next(); // state becomes [3, 7, 9, 15, 20], return 7
bSTIterator.hasNext(); // return true
bSTIterator.next(); // state becomes [3, 7, 9, 15, 20], return 9
bSTIterator.next(); // state becomes [3, 7, 9, 15, 20], return 15
bSTIterator.next(); // state becomes [3, 7, 9, 15, 20], return 20
bSTIterator.hasNext(); // return false
bSTIterator.hasPrev(); // return true
bSTIterator.prev(); // state becomes [3, 7, 9, 15, 20], return 15
bSTIterator.prev(); // state becomes [3, 7, 9, 15, 20], return 9
Constraints:
- The number of nodes in the tree is in the range
[1, 10^5]. 0 <= Node.val <= 10^6- At most
10^5calls will be made tohasNext,next,hasPrev, andprev.
Follow up: Could you solve the problem without precalculating the values of the tree?
Solution
Approach: Lazy In-Order Walk + History of Values
The usual BST iterator keeps a stack of the nodes on the path to the next value, which only moves forward. To also move back, remember every value we have already returned, in order, in a list vals, and keep a pointer i into it (starting at -1, before the smallest value).
next(): moveione step right. Ifiis still insidevals, we are replaying values seen before (after someprev()calls), so just returnvals[i]. Ifi == len(vals), fetch a new value from the in-order walk: pop a node from the stack, push the left chain of its right child, append its value tovalsand return it.hasNext(): true if there is a stored value afterior the stack still has nodes.prev(): moveione step left and returnvals[i].hasPrev(): true ifi > 0. Note it isi > 0, noti >= 0: at the smallest value there is nothing to the left.
This answers the follow-up: the tree is not flattened up front, and values are only computed when next() first reaches them. The walk uses an explicit stack, so a very deep tree does not overflow the call stack.
Complexity: next() is O(1) amortized and the other calls are O(1). Extra space is O(n) in the worst case for vals plus O(h) for the stack, where h is the height of the tree.
class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
self.vals = [] # values already reached, in sorted order
self.i = -1 # the pointer: index into vals
self.stack = [] # pending nodes of the lazy in-order walk
self._push_left(root)
def _push_left(self, node: Optional[TreeNode]) -> None:
while node:
self.stack.append(node)
node = node.left
def hasNext(self) -> bool:
return self.i + 1 < len(self.vals) or len(self.stack) > 0
def next(self) -> int:
self.i += 1
if self.i == len(self.vals):
# step past everything seen so far: take one more node from the walk
node = self.stack.pop()
self._push_left(node.right)
self.vals.append(node.val)
return self.vals[self.i]
def hasPrev(self) -> bool:
return self.i > 0
def prev(self) -> int:
self.i -= 1
return self.vals[self.i]