Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
The first call to next() will return the smallest number in BST. Calling next() again will return the next smallest number in the BST, and so on.
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree. Try to optimize the additional space complexity apart from the amortized time complexity.
Solution:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private Deque<TreeNode> stack;
private TreeNode curr;
public Solution(TreeNode root) {
stack = new ArrayDeque<>();
curr = root;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return curr != null || !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
while (curr != null) {
stack.push(curr);
curr = curr.left;
}
TreeNode next = stack.pop();
curr = next.right;
return next.val;
}
}
/**
* Your Solution will be called like this:
* Solution i = new Solution(root);
* while (i.hasNext()) System.out.print(i.next());
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class BSTIterator {
private Deque<TreeNode> stack;
private TreeNode node;
public BSTIterator(TreeNode root) {
stack = new ArrayDeque<TreeNode>();
node = root;
}
/** @return the next smallest number */
public int next() {
while (node != null) {
stack.push(node);
node = node.left;
}
TreeNode next = stack.pop();
node = next.right;
return next.val;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty() || node != null;
}
// private Stack<TreeNode> stack = new Stack<TreeNode>();
// public BSTIterator(TreeNode root) {
// pushAll(root);
// }
// /** @return whether we have a next smallest number */
// public boolean hasNext() {
// return !stack.isEmpty();
// }
// /** @return the next smallest number */
// public int next() {
// TreeNode tmpNode = stack.pop();
// pushAll(tmpNode.right);
// return tmpNode.val;
// }
// private void pushAll(TreeNode node) {
// for (; node != null; stack.push(node), node = node.left);
// }
}
/**
* 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();
*/