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, 中序遍历BST。
1.初始化根节点非空则入栈,遍历其左子树入栈。
2.hasNext()中判断stack是否为空,非空则调用next()方法。
3.pop栈顶节点node,节点的val即为the next smallest,若node的右节点非空则将其压入栈,然后遍历该节点的左子树入栈。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator {
TreeNode node=null;
Stack<TreeNode> stack=new Stack<TreeNode>();
public BSTIterator(TreeNode root) {
if(root!=null){
stack.push(root);
node=root;
while(node.left!=null){
stack.push(node.left);
node=node.left;
}
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
if(!stack.isEmpty()){
return true;
}
return false;
}
/** @return the next smallest number */
public int next() {
node=stack.pop();
int result=node.val;
if(node.right!=null){
stack.push(node.right);
node=node.right;
while(node.left!=null){
stack.push(node.left);
node=node.left;
}
}
return result;
}
}