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^50 <= Node.val <= 10^6next() is only called when a value is left.