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 atroot.next()returns the next smallest value that has not been returned yet.has_next()(hasNextin 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() → falseConstraints
1 <= number of nodes <= 10^50 <= Node.val <= 10^6next()is only called when a value is left.