173. Binary Search Tree Iterator
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Callingnext()will return the next smallest number in the BST.
Note:next()andhasNext()should run in average O(1) time and uses O(h) memory, wherehis the height of the tree.
Analysis:
Recall how iterative in-order traverse is done:
//sudo code
while (cur != null || stack is not empty)
while(cur is not null)
stack.push(cur);
cur = cur.left;
visit(stack.pop()); // visit node
cur = cur.right;
We basically need to conduct a cycle starting at line "visit node" when "next()" is called till right before visit node line.
When "hasNext()" is called, we just see if stack is empty.
Complexity:
Time: O(1) on average, as in total we need to push N nodes in stack, while next is called n times, the complexity for each time is O(1)
Space: O(logn)
Code:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator {
Deque<TreeNode> stack;
public BSTIterator(TreeNode root) {
stack = new LinkedList<TreeNode>();
while(root!=null)
{
stack.push(root);
root = root.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode returnNode = stack.pop();
TreeNode cur = returnNode.right;
while(cur != null)
{
stack.push(cur);
cur = cur.left;
}
return returnNode.val;
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/