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()
and hasNext()
should
run in average O(1) time and uses O(h) memory, where h is the height of the tree.
這道題主要考察利用Stack對BFS實現inorder traverse.
public class BSTIterator {
//use this stack to push the treeNode into the stack.
Stack<TreeNode> stack = Stack<TreeNode>();
public BSTIterator(TreeNode root) {
treeNode tem = root;
//first judge if the node is null, then if the node is not null, then push it into the stack
while(tem != null){
stack.push(tem);
tem = tem.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode minimum = (TreeNode)stack.pop();
int result = minimum.val;
TreeNode tem = minimum.right;
while(tem != null){
stack.push(tem);
tem = tem.left;
}
return result;
}
}