题解 | 「力扣」第 173 题:二叉搜索树迭代器

151 阅读1分钟

摘要:首先需要理解迭代器是什么意思,迭代器是一个缓存,迭代器的底层是一个线性数据结构,迭代器有两个接口:是否有元素,和返回下一个元素。

题解 | 「力扣」第 173 题:二叉搜索树迭代器

关键:表示一个按中序遍历二叉搜索树(BST)的迭代器

思路:

  • 不停地向左边走,类似第 94 题;
  • 深度优先遍历,后进先出,所以需要使用到栈。
import java.util.ArrayDeque;
import java.util.Deque;


public class BSTIterator {

    private Deque<TreeNode> stack;

    /**
     * 构造函数
     *
     * @param root
     */
    public BSTIterator(TreeNode root) {
        stack = new ArrayDeque<>();

        TreeNode curNode = root;
        while (curNode != null) {
            stack.addLast(curNode);
            curNode = curNode.left;
        }
    }

    /**
     * @return the next smallest number
     */
    public int next() {
        TreeNode top = stack.removeLast();
        if (top.right != null) {
            TreeNode p = top.right;
            while (p != null) {
                stack.addLast(p);
                p = p.left;
            }
        }
        return top.val;
    }

    /**
     * @return whether we have a next smallest number
     */
    public boolean hasNext() {
        return !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();
 */