173. Binary Search Tree Iterator
Description
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next()
will return the next smallest number in the BST.
Note:
next()
andhasNext()
should run in average O(1) time and uses O(h) memory, where h is the height of the tree.You may assume that
next()
call will always be valid, that is, there will be at least a next smallest number in the BST whennext()
is called.
Constraints
Approach
Links
GeeksforGeeks
YouTube
Examples
Input:
["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext
[[[7, 3, 15, null, null, 9, 20]], [null], [null], [null], [null], [null], [null], [null], [null], [null]]

Output:
[null, 3, 7, true, 9, true, 15, true, 20, false]
Explanation:

Solutions
/**
* Time complexity :
* Space complexity :
*/
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator obj = new BSTIterator(root);
* int param_1 = obj.next();
* boolean param_2 = obj.hasNext();
*/
class BSTIterator {
private Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
stack = new Stack<TreeNode>();
pushNodes(root);
}
/** @return the next smallest number */
public int next() {
TreeNode root = stack.pop();
pushNodes(root.right);
return root.val;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
private void pushNodes(TreeNode root) {
while(root != null) {
stack.push(root);
root = root.left;
}
}
}
Follow up
Last updated
Was this helpful?