Problem:
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.
Explanation:
设计一个迭代器,next()方法可以获得二叉树中下一个最小的元素,hasnext()方法用于判断是否有下一个最小元素。
My Thinking:
维护一个中序遍历的list以及当前元素的index
My Solution:
class BSTIterator {
private List<Integer> list=new ArrayList<>();
private int index=0;
public BSTIterator(TreeNode root) {
inorderTraverse(root);
}
public void inorderTraverse(TreeNode root){
if(root==null)
return;
inorderTraverse(root.left);
list.add(root.val);
inorderTraverse(root.right);
}
/** @return the next smallest number */
public int next() {
return list.get(index++);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return index<list.size();
}
}
Optimum Thinking:
使用栈先存放所有左结点,每次弹出一个结点再将其右孩子入栈,同时返回当前结点的值
Optimum Solution:
public class BSTIterator {
private Stack<TreeNode> stack = new Stack<TreeNode>();
public BSTIterator(TreeNode root) {
pushAll(root);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode tmpNode = stack.pop();
pushAll(tmpNode.right);
return tmpNode.val;
}
private void pushAll(TreeNode node) {
while(node!=null){
stack.push(node);
node = node.left;
}
}
}