Skip to main content

🟡 剑指 Offer II 055. 二叉搜索树迭代器

LeetCode 提示

题目难度 中等

原题链接 🔗 leetcode

题解1#

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode() {} *     TreeNode(int val) { this.val = val; } *     TreeNode(int val, TreeNode left, TreeNode right) { *         this.val = val; *         this.left = left; *         this.right = right; *     } * } */class BSTIterator {    private Deque<Integer> stack;
    private void visit(TreeNode node) {        if (node.left != null) {            visit(node.left);        }        stack.add(node.val);        if (node.right != null) {            visit(node.right);        }    }
    public BSTIterator(TreeNode root) {        this.stack = new ArrayDeque<>();        visit(root);    }        public int next() {        return this.stack.poll();    }        public boolean hasNext() {        return !this.stack.isEmpty();    }}
/** * Your BSTIterator object will be instantiated and called as such: * BSTIterator obj = new BSTIterator(root); * int param_1 = obj.next(); * boolean param_2 = obj.hasNext(); */