Practice Binary Search Tree Iterator
Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.
Binary Search Tree Iterator
Problem Statement
BSTIterator(root) traverses a binary search tree in in-order sequence, starting before its first value. next() advances and returns the next value; hasNext() reports whether a value remains. Every next call is guaranteed valid. Practice approach: Keep a stack containing the unexplored left path. next pops its last node, then pushes the left path of that node's right child. The first result is the smallest value. Across traversal, each node is pushed and popped once, giving amortized O(1) next and O(1) hasNext with O(h) auxiliary memory, where h is tree height.
Source: Binary Search Tree Iterator on LeetCode. Use the original task for its coding environment and submissions.
Examples
# Example 1
["BSTIterator","hasNext","next","next","hasNext","next","hasNext"] [[[4,2,6]],[],[],[],[],[],[]]
[null,true,2,4,true,6,false]
The tree yields 2, 4, 6. hasNext becomes false only after 6 has been returned.
Constraints
Related LeetCode Problems
Practice more problems similar to Binary Search Tree Iterator.
Review your practice with PhantomCodeAI
After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.