DSAVisualiseData Structures & Algorithms Studio
Trees & Ordered Maps Hard

BST In-Order Iterator

The fail-fast BinarySearchTreeIterator stores the tree's left spine on a stack, then returns the next smallest key on each call.

Trace input

Bounded JSON

Edit the lesson input, then build a deterministic source-linked trace.

This lesson validates its own input and operation limits.

Source scenarios

Complexity

BestO(h) iterator initialization
AverageO(h) iterator initialization; O(1) amortized per next
WorstO(h) iterator initialization; O(h) for one next
SpaceO(h) for the iterator stack

Array state

Follow the active comparisons and writes.

Live snapshot

Current operation

Trace state
Ready to explore
Source behavior & common mistakes

Follow unique-key insertion, subtree-size updates, lazy left-spine initialization, and stack-based inorder traversal. The iterator checks the captured tree size before hasNext and next.

  • Duplicate keys are ignored: put only descends left for cmp < 0 and right for cmp > 0.
  • Each recursive put recomputes subtree size even when the key is a duplicate.
  • The iterator constructor pushes the root-to-leftmost path; the stack top is the next key.
  • After popping a node, next pushes the left spine of its right subtree.
  • Both hasNext and next check whether tree size changed; inserting an existing key does not invalidate the iterator because size remains unchanged.
  • Calling next after the stack is empty throws NoSuchElementException.

Algorithm code

Java
BinarySearchTreeIterator.java (pinned repository source)Step linked
The highlighted line follows the current step.

Ready to begin

Press Play to see what happens.

Detailed execution
Snapshot 1 / 1
Visited 0