15% off all plans & roadmaps Use code

See plans

Binary Search Tree Iterator

Updated

TL;DR: The iterator must return BST values in sorted order, one call at a time. Keep the pending ancestors on an explicit stack, so each next() call does only the work it needs and memory stays at O(h).

Problem

Implement the BSTIterator class. It iterates over the in-order traversal of a binary search tree (BST).

  • BSTIterator(TreeNode root) builds the iterator from the tree's root. The pointer starts at a value smaller than every element in the BST.
  • boolean hasNext() returns true if the traversal has a number to the right of the pointer. Otherwise it returns false.
  • int next() moves the pointer to the right and returns the number at the pointer.

Because the pointer starts before the smallest element, the first call to next() returns the smallest element in the BST.

You may assume every next() call is valid. The traversal always has at least one more number when next() runs.

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]
Explanation:
- bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20])
- next() returns 3
- next() returns 7
- hasNext() returns true
- next() returns 9
- hasNext() returns true
- next() returns 15
- hasNext() returns true
- next() returns 20
- hasNext() returns false

Constraints

  • The number of nodes in the tree is in the range [1, 10^5].
  • 0 <= Node.val <= 10^6
  • At most 10^5 calls will be made to hasNext and next.

Constraints that matter

  • The tree can hold up to 10^5 nodes, so an O(N) list is correct but uses memory the follow-up forbids.
  • The follow-up asks for O(h) memory, which rules out copying every value in the constructor.
  • Up to 10^5 calls mix next and hasNext. Re-walking the tree per call would cost up to 10^10 steps, so each call must be cheap on average.
  • Values are never compared by the iterator. Only the tree's shape and the in-order order matter.

View on LeetCode

Hints

Hint 1

A BST's in-order traversal (left subtree, node, right subtree) produces its values in sorted order.

Hint 2

The naive iterator walks the whole tree in the constructor and copies every value into a list.

Solution

Intuition

A BST's in-order traversal (left subtree, node, right subtree) produces its values in sorted order. The problem asks for those values one at a time, so the walk has to be an iterator. A recursive in-order traversal does this with the call stack. An iterator cannot rely on the call stack, because it must return a value and pause between calls.

Picture a stack of sticky notes, one per ancestor you still owe a visit. Each next() call peels off the top note, reports its value, then adds notes for the left edge of that node's right branch.

So the iterator keeps the stack as an explicit field. The stack holds the nodes that wait for their turn. A node waits while its left subtree is still being processed. When it is popped, its own value is the next one, and its right subtree comes after it.

Recognize this pattern when a problem asks for in-order output, a lazy sequence from a BST, or the k-th smallest value. The technique is recursive inorder traversal with an explicit stack, which belongs to Tree DFS. Prerequisites: you need the three in-order steps and the idea that a stack stores pending work.

Watch the pattern animation

Worked example

Input: root = [1]. Calls: BSTIterator(root), then next(), then hasNext().
Output: [null, 1, false]
Explanation: The tree has one node, so the traversal is only 1. The first next() returns 1 and moves the pointer onto it. After that, no numbers remain to the right, so hasNext() returns false. The example is small, so the dry runs show the mechanics, and the statement tree shows the right-subtree step.

Approach 1: Brute force: copy every value into a list

The naive iterator walks the whole tree in the constructor and copies every value into a list. Then next() reads the list in order. No sorting is needed, because an in-order walk of a BST already yields sorted values. The walk still touches all N nodes before the first call returns, and it holds all N values in memory at once.

Steps

  1. In the constructor, walk the tree in order and append each node's value to a list.
  2. Set the index to -1, so the pointer sits before the first element.
  3. In next(), increment the index and return the value at that index.
  4. In hasNext(), return true while index + 1 is less than the list length.

Dry run

The constructor walks the root 1 and appends 1, so values = [1] and index = -1. The first call to next() moves the index to 0 and returns values[0], which is 1. The call to hasNext() checks whether index + 1 = 1 is less than the length 1, and it is not, so it returns false. The output is [null, 1, false], which matches the example.

Complexity

TimeO(N) constructor, O(1) per next and hasNext
SpaceO(N)

Let N be the number of nodes. The constructor visits each node once and appends it once, so its work is O(N). Each next and hasNext performs a fixed number of index operations and one array read, so each is O(1). The list stores one value per node, so the space is O(N), which is exactly the cost the follow-up rejects.

PythonTested in our runner

from typing import List, Optional

class BSTIterator:
    def __init__(self, root: Optional[TreeNode]):
        # Walk the tree in order once and store every value
        self.values: List[int] = []
        stack = []
        node = root
        while node or stack:
            while node:
                stack.append(node)
                node = node.left
            node = stack.pop()
            self.values.append(node.val)
            node = node.right
        self.index = -1

    def next(self) -> int:
        self.index += 1
        return self.values[self.index]

    def hasNext(self) -> bool:
        return self.index + 1 < len(self.values)

The Recursive Inorder Traversal infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Recursive Inorder Traversal

Part of Tree Traversal Patterns (DFS & BFS)

Approach 2: Lazy in-order walk with an explicit stackOptimalRecursive Inorder Traversal

What's slow: the list approach does all N steps before the first call returns, and it keeps all N values even when the caller reads only a few. The insight that fixes it: between calls, the only state you need is the set of nodes still waiting for their turn. Keep those nodes on a stack and do one step of the in-order walk per call.

A stack returns the most recently pushed node first. That matches in-order order here, because the last waiting node is the smallest unprocessed one. When you return a node, its right subtree is next, so you push that subtree's left spine.

Why it is correct. The invariant is that the stack holds exactly the ancestors still waiting for their turn, with the smallest unreturned value on top. A node is popped only after its entire left subtree has been returned, so nothing smaller is still pending. Its right subtree holds only larger values, so pushing that subtree's left spine keeps the order correct.

Steps

  1. In the constructor, start at the root and push it and every left child down to the leftmost node.
  2. In hasNext(), return true if the stack is not empty.
  3. In next(), pop the top node. Its value is the number to return.
  4. Take the popped node's right child and push it and its whole left spine.
  5. Return the popped node's value.

Dry run

StepActionStack (top on the right)Returned
1Constructor pushes root 1. Its left child is null, so the spine ends.[1]none
2next() pops 1. Its right child is null, so nothing is pushed.[]1
3hasNext() finds the stack empty.[]false

The output is [null, 1, false], which matches the example.

Complexity

TimeO(h) constructor, amortized O(1) per call
SpaceO(h)

Let n be the number of nodes and h the height. The constructor walks one left spine, at most h nodes, and each node is pushed once and popped once over the whole walk. So n calls do O(n) total push and pop work, which is amortized O(1) per call, even though one call can cost O(h) when it pushes a long spine. Those pushes are paid for by nodes popped later and never revisited, and the stack never exceeds h entries because it holds one path down the tree.

PythonTested in our runner

from typing import List, Optional

class BSTIterator:
    def __init__(self, root: Optional[TreeNode]):
        self.stack: List[TreeNode] = []
        self._push_left(root)

    def _push_left(self, node: Optional[TreeNode]) -> None:
        # Push node and its whole left spine
        while node:
            self.stack.append(node)
            node = node.left

    def next(self) -> int:
        top = self.stack.pop()
        # The right subtree is next in order, so push its left spine
        self._push_left(top.right)
        return top.val

    def hasNext(self) -> bool:
        return len(self.stack) > 0

Common mistakes

  • this.pushLeft(top.left) inside next(). The left subtree of the popped node is already finished, so pushing it returns values twice. Push top.right and its left spine instead.
  • stack.push(top.right) without the left descent. The right subtree's smallest node is deeper, so next() returns a larger value first. Walk left from top.right until null.
  • Starting the list index at 0 instead of -1 in the list version. The first next() then skips values[0]. The pointer starts before the first element, so the index must start at -1.
  • Checking index < values.size() in hasNext. After the last next(), this returns true and the following call reads past the end. Compare index + 1 with the size.
  • Calling top() or pop() in hasNext or before the emptiness check. An empty stack has no top, so hasNext must only test emptiness.
  • Using a recursive helper for the list walk in Python or Java. A chain of 10^5 nodes can reach that recursion depth and overflow the stack. Use the explicit loop shown in the code.

Edge cases

  • A single node, root = [1]: next() returns 1, then hasNext() returns false.
  • A root with only a right child, such as [1, null, 2]: next() returns 1, then the right child is pushed inside the next call, so next() returns 2 and hasNext() returns false.
  • A left-skewed chain of 10^5 nodes: the constructor pushes every node, so the stack holds about N = h entries, which is still correct.
  • A right-skewed chain: each next() pops one node and pushes at most one, so the stack never holds more than one node.
  • Values 0 and 10^6 both appear: the stack tracks emptiness, not a sentinel value, so no special value is needed.
  • Duplicate values: in-order traversal of a valid BST is non-decreasing, and the stack walk returns the same sequence the list would.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Binary Search Tree Iterator, with how to answer them.

Unlock the follow-ups

Binary Search Tree Iterator FAQ

What is the time complexity of Binary Search Tree Iterator?

The constructor takes O(h) time, where h is the tree height. Each next call takes amortized O(1) time, and hasNext takes O(1). Across the whole traversal, every node is pushed once and popped once.

Why use a stack for Binary Search Tree Iterator?

A stack stores the nodes that still wait for their turn, so the walk can pause between calls. It replaces the call stack that a recursive inorder traversal uses. Without it, the iterator would have to rebuild the path from the root on every call.

Can Binary Search Tree Iterator be solved in O(1) extra space?

Yes, with Morris traversal. That method temporarily rewires the tree and restores it, which makes it harder to use safely. The stack version uses O(h) space and leaves the tree unchanged, so it is the usual interview answer.

Can you use BFS for this problem?

Not directly. Level order traversal returns nodes by depth, not by value, so it does not give sorted output. The in-order DFS is the traversal that matches the BST order.

Why does the list version fail the follow-up?

It copies every value in the constructor, so memory grows with N even if the caller reads only two values. The follow-up asks for O(h) memory, and the lazy stack provides that.

Asked at

See which companies ask this — Pro

Practise it