Binary Search Tree Iterator

Medium · Trees · Stack · Tree · Design · Binary Search Tree · Iterator

Problem

Implement a class BSTIterator that walks a binary search tree in in-order (increasing) order:

next() is only called when a value is left. Aim for next() and hasNext() in amortized O(1) time using O(h) memory, where h is the height of the tree.

Tests replay a call sequence: the first entry builds the iterator from the tree given as a level-order list (None marks a missing child), each later entry is a method call, and the constructor reports None. TreeNode, from_level() and to_level() are already defined.

Examples

Input: ops = ["BSTIterator","next","next","hasNext","next","hasNext"], args = [[[5,2,9]],[],[],[],[],[]]
Output: [null,2,5,true,9,false]

The values come out as 2, 5, 9, after which nothing is left.

Input: ops = ["BSTIterator","hasNext","next","hasNext"], args = [[[4]],[],[],[]]
Output: [null,true,4,false]

A single-node tree yields one value.

Input: ops = ["BSTIterator","next","next","hasNext","next","hasNext","next","next","hasNext"], args = [[[7,3,15,None,None,9,20]],[],[],[],[],[],[],[],[]]
Output: [null,3,7,true,9,true,15,20,false]

The values come out as 3, 7, 9, 15, 20; hasNext() is True until the last one is read.

Constraints

Approaches

Follow-up

The stack is the recursion of an in-order traversal, paused between values. A descending iterator is the mirror image (push right spines). The use cases put sorted order to work: the smallest gap between neighbors in one BST, and two iterators merging two BSTs.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…