173. Binary Search Tree Iterator LeetCode Solution
In this guide, you will get 173. Binary Search Tree Iterator LeetCode Solution with the best time and space complexity. The solution to Binary Search Tree Iterator problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Binary Search Tree Iterator solution in C++
- Binary Search Tree Iterator solution in Java
- Binary Search Tree Iterator solution in Python
- Additional Resources
Problem Statement of Binary Search Tree Iterator
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.
Example 1:
Input
[“BSTIterator”, “next”, “next”, “hasNext”, “next”, “hasNext”, “next”, “hasNext”, “next”, “hasNext”]
[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
Output
[null, 3, 7, true, 9, true, 15, true, 20, false]
Explanation
BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);
bSTIterator.next(); // return 3
bSTIterator.next(); // return 7
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 9
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 15
bSTIterator.hasNext(); // return True
bSTIterator.next(); // return 20
bSTIterator.hasNext(); // return False
Constraints:
The number of nodes in the tree is in the range [1, 105].
0 <= Node.val <= 106
At most 105 calls will be made to hasNext, and next.
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?
Complexity Analysis
- Time Complexity: O(1)
- Space Complexity: O(n)
173. Binary Search Tree Iterator LeetCode Solution in C++
class BSTIterator {
public:
BSTIterator(TreeNode* root) {
inorder(root);
}
int next() {
return vals[i++];
}
bool hasNext() {
return i < vals.size();
}
private:
int i = 0;
vector<int> vals;
void inorder(TreeNode* root) {
if (root == nullptr)
return;
inorder(root->left);
vals.push_back(root->val);
inorder(root->right);
}
};
/* code provided by PROGIEZ */
173. Binary Search Tree Iterator LeetCode Solution in Java
class BSTIterator {
public BSTIterator(TreeNode root) {
inorder(root);
}
public int next() {
return vals.get(i++);
}
public boolean hasNext() {
return i < vals.size();
}
private int i = 0;
private List<Integer> vals = new ArrayList<>();
private void inorder(TreeNode root) {
if (root == null)
return;
inorder(root.left);
vals.add(root.val);
inorder(root.right);
}
}
// code provided by PROGIEZ
173. Binary Search Tree Iterator LeetCode Solution in Python
class BSTIterator:
def __init__(self, root: TreeNode | None):
self.i = 0
self.vals = []
self._inorder(root)
def next(self) -> int:
self.i += 1
return self.vals[self.i - 1]
def hasNext(self) -> bool:
return self.i < len(self.vals)
def _inorder(self, root: TreeNode | None) -> None:
if not root:
return
self._inorder(root.left)
self.vals.append(root.val)
self._inorder(root.right)
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.