
Problem
Solution
Submissions
Iterator for a Binary Search Tree
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 12
Write a C# program to implement an iterator for a binary search tree (BST) with the following operations:
1. BSTIterator(TreeNode root)
: Initialize an iterator with the root of a BST.
2. bool HasNext()
: Return true if there is a next element in the iteration.
3. int Next()
: Return the next smallest element in the BST.
The iterator should follow the in-order traversal of the BST (left-root-right).
Example 1
- Input: root = [7, 3, 15, null, null, 9, 20]
- Operations:
- bSTIterator = new BSTIterator(root);
- bSTIterator.Next(); // return 3
- bSTIterator.Next(); // return 7
- bSTIterator.HasNext(); // return true
- bSTIterator.Next(); // return 9
- bSTIterator.Next(); // return 15
- bSTIterator.Next(); // return 20
- bSTIterator.HasNext(); // return false
Example 2
- Input: root = [1, null, 3, null, null, 2, null]
- Operations:
- bSTIterator = new BSTIterator(root);
- bSTIterator.HasNext(); // return true
- bSTIterator.Next(); // return 1
- bSTIterator.Next(); // return 2
- bSTIterator.Next(); // return 3
- bSTIterator.HasNext(); // return false
Constraints
- The number of nodes in the tree is in the range [1, 10^5]
- 0 ≤ Node.val ≤ 10^6
- At most 10^5 calls will be made to HasNext and Next
- Time Complexity: O(1) average time per operation
- Space Complexity: O(h) where h is the height of the tree
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a stack to keep track of nodes
- Initialize the stack by pushing all leftmost nodes
- To get the next smallest element, pop the top of the stack
- After popping a node, push all leftmost nodes of its right child
- The HasNext method checks if the stack is empty