Problem
Section titled “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 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.
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.
Example 1:

Input["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"][[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]Output[null, 3, 7, true, 9, true, 15, true, 20, false]
ExplanationBSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);bSTIterator.next(); // return 3bSTIterator.next(); // return 7bSTIterator.hasNext(); // return TruebSTIterator.next(); // return 9bSTIterator.hasNext(); // return TruebSTIterator.next(); // return 15bSTIterator.hasNext(); // return TruebSTIterator.next(); // return 20bSTIterator.hasNext(); // return FalseConstraints:
- The number of nodes in the tree is in the range .
-
Node.val - At most calls will be made to
hasNext, andnext.
Follow-up: Could you implement next() and hasNext() to run in average time and use memory, where is the height of the tree?
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”Copying the whole in-order sequence into an array in the constructor would make next() trivial, but it uses memory. The follow-up asks for , so we must produce the sequence lazily: run the iterative in-order traversal, but pause it after each value.
In an iterative in-order traversal, the stack holds exactly the nodes whose left subtree is being (or has been) explored but which have not been output yet. That is the left spine of the remaining part of the tree:
- The smallest unvisited node is always on top of the stack.
- After outputting a node, its in-order successor is the leftmost node of its right subtree (if it has one), so we push the left spine of
node->right. Otherwise the successor is the next node on the stack, an ancestor whose left subtree we have just finished.
The stack never holds more than one node per level, so its size is at most .
Algorithm
Section titled “Algorithm”pushLeft(node)pushesnode,node->left,node->left->left, … until it reachesnullptr.- The constructor calls
pushLeft(root). next()pops the top nodenode, callspushLeft(node->right), and returnsnode->val.hasNext()returns whether the stack is non-empty.
Walkthrough
Section titled “Walkthrough”Example 1 (tree [7, 3, 15, null, null, 9, 20]), stack shown bottom to top:
| Call | Popped | Pushed (pushLeft) | Stack after | Returns |
|---|---|---|---|---|
| constructor | — | 7, 3 | [7, 3] | — |
next() | 3 | — | [7] | 3 |
next() | 7 | 15, 9 | [15, 9] | 7 |
next() | 9 | — | [15] | 9 |
next() | 15 | 20 | [20] | 15 |
next() | 20 | — | [] | 20 |
hasNext() | — | — | [] | false |
Complexity
Section titled “Complexity”- Time: amortised per call —
hasNext()is ;next()can push up to nodes once, but every node is pushed and popped exactly once over the whole iteration, so calls cost in total. - Space: — the stack holds at most one node per level.
Edge cases
Section titled “Edge cases”- Single node: the constructor pushes it, the first
next()returns it, andhasNext()then returnsfalse. - Skewed tree (a left chain): the constructor pushes all nodes; each
next()is then a single pop, matching the memory bound.
Think before you peek
Work out an approach on your own first — the explanation will still be here when you want it.
class BSTIterator { stack<TreeNode*> st;
void pushLeft(TreeNode* node) { for (; node; node = node->left) st.push(node); }
public: BSTIterator(TreeNode* root) { pushLeft(root); }
int next() { TreeNode* node = st.top(); st.pop(); pushLeft(node->right); return node->val; }
bool hasNext() { return !st.empty(); }};class BSTIterator { private final ArrayDeque<TreeNode> st = new ArrayDeque<>();
public BSTIterator(TreeNode root) { pushLeft(root); }
public int next() { TreeNode node = st.pop(); pushLeft(node.right); return node.val; }
public boolean hasNext() { return !st.isEmpty(); }
private void pushLeft(TreeNode node) { for (; node != null; node = node.left) st.push(node); }}class BSTIterator:
def __init__(self, root: TreeNode | None): self.st = [] self._push_left(root)
def _push_left(self, node): while node: self.st.append(node) node = node.left
def next(self) -> int: node = self.st.pop() self._push_left(node.right) return node.val
def hasNext(self) -> bool: return bool(self.st)Give it a try first
Attempt the problem on LeetCode — the code will still be here.