leetcode 173 二叉搜索树迭代器

题目链接: https://leetcode-cn.com/problems/binary-search-tree-iterator/

class BSTIterator {
    Stack<TreeNode> stack = new Stack<>();
    TreeNode cur;

    public BSTIterator(TreeNode root) {
        cur = root;
    }

    public int next() {
        while (cur != null) {
            stack.push(cur);
            cur = cur.left;
        }
        cur = stack.pop();
        int res = cur.val;
        cur = cur.right;
        return res;
    }

    public boolean hasNext() {
        return cur != null || !stack.isEmpty();
    }
}

原创文章,作者:ifee,如若转载,请注明出处:https://www.ifee.win/blog/2021/07/29/leetcode-173-%e4%ba%8c%e5%8f%89%e6%90%9c%e7%b4%a2%e6%a0%91%e8%bf%ad%e4%bb%a3%e5%99%a8/

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注