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.
5
/ \
3 7
/ \ / \
2 4 6 8
这道题的思路是初始的时候用一个Stack存从根节点开始所有的左子树节点。以上图为例,初始化过后Stack会存有 |5|3|2|,然后将节点从Stack中一个个弹出来,每弹出一个节点(比如3)的时候要将右子树入栈,这样就保证了左->中->右的访问顺序, 也就是BST的排序。
public class BinarySearchTreeIterator {
Stack<TreeNode> stack = new Stack<TreeNode>();
public BinarySearchTreeIterator(TreeNode root) {
pushLeftNode(root);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode smallNode = stack.pop();
pushLeftNode(smallNode.right);
return smallNode.val;
}
private void pushLeftNode(TreeNode node) {
TreeNode current = node;
while (current!=null) {
stack.push(current);
current = current.left;
}
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/