Skip to content
Decoder

Binary Search Tree Iterator

Medium

Problem

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.

Example 1

Tree [12, 5, 18, 2, 8, null, 25]

Example 2

it = BSTIterator(root)

Example 3

Input
it.has_next()
Output
true

Example 4

Input
it.next()
Output
2

Example 5

Input
it.next()
Output
5

Example 6

Input
it.next()
Output
8

Example 7

Input
it.has_next()
Output
true

Example 8

Input
it.next()
Output
12

Example 9

Input
it.next()
Output
18

Example 10

Input
it.next()
Output
25

Example 11

Input
it.has_next()
Output
false

Constraints

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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.