173. 二叉搜索树迭代器


通过一个优先队列进行存储数据 然后每一次读数据都是输出第一个结点

class BSTIterator {
    Queuels = new PriorityQueue();
    public BSTIterator(TreeNode root) {
        dfs(root);
    }
    public void dfs(TreeNode root) {
        if(root==null) {return ;}
        ls.add(root.val);
        if(root.left!=null)dfs(root.left);
        if(root.right!=null)dfs(root.right);
    }
    /** @return the next smallest number */
    public int next() {
        return ls.poll();
    }
    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        if(ls.size() == 0)
            return false;
        else return true;
    }
}

中序遍历+栈模拟

class BSTIterator {
    Stack stack = new Stack();
    public BSTIterator(TreeNode root) {
        stack.clear();
        while(root!=null) {
            stack.add(root);
            root = root.left;
        }
    }

    /** @return the next smallest number */
    public int next() {
        TreeNode p = stack.pop();
        int res = p .val;
        p = p.right;
        while(p!=null) {
            stack.add(p);
            p = p.left;
        }
        return res;
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return !stack.isEmpty();
    }
}
全部评论

相关推荐

白火同学:大二有这水平很牛了,可以适当对关键信息加粗一点,比如关键技术、性能指标之类的。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务