173. 二叉搜索树迭代器(迭代模拟中序遍历)

135 阅读1分钟

  • 用栈进行迭代
class BSTIterator {
        private Stack<TreeNode> stack = new Stack<>();
        public BSTIterator(TreeNode root) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
        }

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

        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            return !stack.isEmpty();
        }
}
  • 用数组此时空间复杂度是O(结点数)而不是O(H树的高度)
class BSTIterator {
        private List<Integer> list = new ArrayList<>();
        private int pos = 0;
        public BSTIterator(TreeNode root) {
            dfs(root);
        }

        private void dfs(TreeNode root) {
            if (root == null) {
                return;
            }
            dfs(root.left);
            list.add(root.val);
            dfs(root.right);
        }

        /** @return the next smallest number */
        public int next() {
            return list.get(pos++);
        }

        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            return pos < list.size();
        }
    }