Binary Search Tree Iterator
lc 173
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.
这个题关键有个cur 的全局变量node,时刻知道现在哪里了。然后有个stack全局变量,inorder 走就行了。
public class BSTIterator {
private Stack<TreeNode> stack = new Stack<>();
private TreeNode cur;
public BSTIterator(TreeNode root) {
cur = root;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return( cur != null || !stack.isEmpty());
}
/** @return the next smallest number */
public int next() {
while(cur != null){
stack.push(cur);
cur = cur.left;
}
TreeNode temp = stack.pop();
cur = temp.right;
return temp.val;
}
}