Skip to content

Binary Search Tree Iterator

MediumStack
Decode it first. Clues, constraints, pattern and plan before any code.

Build a class BSTIterator that walks a binary search tree in increasing order, one value per call.

  • BSTIterator(root) starts the iterator on the tree rooted at root.
  • next() returns the next smallest value that has not been returned yet.
  • has_next() (hasNext in TypeScript) returns whether any values are left.

Both calls should take O(1) time on average, and the iterator should use O(h) memory, where h is the height of the tree, so copying every value into a list up front is not allowed.

Tree [12, 5, 18, 2, 8, null, 25]
 
it = BSTIterator(root)
it.has_next()   →  true
it.next()       →  2
it.next()       →  5
it.next()       →  8
it.has_next()   →  true
it.next()       →  12
it.next()       →  18
it.next()       →  25
it.has_next()   →  false

Constraints

  • 1 <= number of nodes <= 10^5
  • 0 <= Node.val <= 10^6
  • next() is only called when a value is left.