AAlgoLoopSpaced repetition for LeetCode
MEDIUMDesignLeetCode ↗

Binary Search Tree Iterator

The key idea

Simulate an in-order traversal lazily with an explicit stack. Push the whole left spine on construction; each 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

Examples

Input: ["BSTIterator","next","next","hasNext","next","hasNext"] [[[7,3,15,null,null,9,20]],[],[],[],[],[]] Output: [null,3,7,true,9,true]
Input: ["BSTIterator","next","hasNext","next","hasNext"] [[[2,1,3]],[],[],[],[]] Output: [null,1,true,2,true]

Complexity

Time: O(1) amortized per next/hasNext Space: O(h)

See the full solution

410310
Step-by-step visualization
Start free →

More Design problems