一亩三分地论坛

 找回密码
 获取更多干货,去instant注册!

扫码关注一亩三分地公众号
查看: 207|回复: 0
收起左侧

[Leetcode] about work in constructoer in Binary Search Tree Iterator

[复制链接] |试试Instant~ |关注本帖
fishriver 发表于 2015-11-5 02:10:56 | 显示全部楼层 |阅读模式

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看,没有帐号?获取更多干货,去instant注册!

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;
    }
}



本版积分规则

请点这里访问我们的新网站:一亩三分地Instant.

Instant搜索更强大,不扣积分,内容组织的更好更整洁!目前仍在beta版本,努力完善中!反馈请点这里

关闭

一亩三分地推荐上一条 /5 下一条

手机版|小黑屋|一亩三分地论坛声明 ( 沪ICP备11015994号 )

custom counter

GMT+8, 2016-12-5 03:45

Powered by Discuz! X3

© 2001-2013 Comsenz Inc. Design By HUXTeam

快速回复 返回顶部 返回列表