注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
本帖最后由 fishriver 于 2015-11-5 02:12 编辑
I checked several others' solutions, but they all make the constructor do some work. Is that good or bad?
Here is the highest voted 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) {
for (; node != null; stack.push(node), node = node.left); }
}
Here is mine: Is it better to keep constructor light?
public class BSTIterator {
private TreeNode node;
private Stack<TreeNode> stack = new Stack<>();
public BSTIterator(TreeNode root) {
node = root;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
while(node != null){
stack.push(node);
node = node.left;
}
if(!stack.isEmpty()){
return true;
}else{
return false;
}
}
/** @return the next smallest number */
public int next() {
TreeNode tmp = stack.pop();
node = tmp.right;
return tmp.val;
}
}
|