Skip to content
Veltoryx Technologies
ProProblem 103● MediumLeetCode #173 ↗4 min readUpdated 30 October 2026

Binary Search Tree Iterator

Implement an iterator over a BST with O(h) memory and O(1) amortized next() operations.

01The 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.

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 must implement next() and hasNext() to run in average O(1) time and use O(h) memory, where h is the height of the tree.

text
       7
      /      3   15
        /         9   20

BSTIterator it = new BSTIterator(root);
it.next();    // 3
it.next();    // 7
it.hasNext(); // true
it.next();    // 9
it.hasNext(); // true
it.next();    // 15
it.hasNext(); // true
it.next();    // 20
it.hasNext(); // 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.

Loading the rest of the lesson…