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.
Solution: BST用inorder traversal。实际就是把stack实现inorder traversal拆开在几个部分
Stack<TreeNode> stack = new Stack<>();
TreeNode curt;
public BSTIterator(TreeNode root) {
curt = root;
while(curt != null){
stack.push(curt);
curt = curt.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.empty();
}
/** @return the next smallest number */
public int next() {
curt = stack.pop();
int val = curt.val;
curt = curt.right;
while(curt != null){
stack.push(curt);
curt = curt.left;
}
return val;
}