Binary Search Tree Iterator
Implement the BSTIterator class over the in-order traversal of a binary search tree. The constructor takes the root. next() returns the next smallest value in the BST, and hasNext() returns true if a next value exists. next() is only called when hasNext() is true.
Open official problem prompt ↗Emit the BST's values in sorted (in-order) order one call at a time, using memory proportional to the tree height, not its size.
Like a bookmark in a recursive walk: instead of reading the whole book at once, you keep a stack of the pages you paused on so you can resume exactly where you left off each time next() is called.
- Input
- ["BSTIterator","next","next","hasNext","next","hasNext","next","hasNext","next","hasNext"] with root = [7,3,15,null,null,9,20]
- Output
- [null,3,7,true,9,true,15,true,20,false]
- Why
- In-order values are 3,7,9,15,20; next() emits them in that order and hasNext() is false only after 20.
The number of nodes is in the range [1, 10^5]0 <= Node.val <= 10^6At most 10^5 calls to next and hasNextnext is called only when hasNext returns true