Binary Search Tree Iterator
The key idea
next pops the top (the current smallest), then pushes the left spine of that node's right child. This keeps next and hasNext cheap and uses only O(h) memory for the spine.Problem
Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):
- BSTIterator(TreeNode root) initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.
- boolean hasNext() returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.
- int next() moves the pointer to the right, then returns the number at the pointer.
Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.
You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.
Follow up: Could you implement next() and hasNext() to run in average O(1) time and use O(h) memory, where h is the height of the tree?
Constraints
- The number of nodes in the tree is in the range
[1, 10^5]. 0 <= Node.val <= 10^6- At most
10^5calls will be made tonextandhasNext.
Examples
Complexity
Time: O(1) amortized per next/hasNext Space: O(h)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Design problems
- Design Circular QueueMEDIUM
- Design HashMapEASY
- Design HashSetEASY
- Design TwitterMEDIUM
- Detect SquaresMEDIUM
- Encode and Decode StringsMEDIUM
- Implement Queue using StacksEASY
- Implement Stack using QueuesEASY
- Insert Delete GetRandom O(1)MEDIUM
- LFU CacheHARD
- LRU CacheMEDIUM
- Maximum Frequency StackHARD