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.
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.
二叉搜索树或者是一棵空树,或者是具有下列性质的二叉树
若左子树不空,则左子树上所有结点的值均小于或等于它的根结点的值
若右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值
左、右子树也分别为二叉排序树
public class BSTIterator {
private Stack<TreeNode> stack = new Stack<TreeNode>();
public BSTIterator(TreeNode root) {
pushLeft(root);
}
private void pushLeft(TreeNode node) {
while(node != null) {
stack.push(node);
node = node.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode n = stack.pop();
pushLeft(n.right);
return n.val;
}
}