Skip to content

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.

Medium#173
LeetCode Problem

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

Input
["BSTIterator","hasNext","next","next","hasNext","next","hasNext"]
[[[4,2,6]],[],[],[],[],[],[]]
Output
[null,true,2,4,true,6,false]
Explanation

The tree yields 2, 4, 6. hasNext becomes false only after 6 has been returned.

Constraints

1 <= number of nodes <= 10^5
0 <= Node.val <= 10^6
At most 10^5 total calls to hasNext and next.

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.