173. Binary Search Tree Iterator

题目描述和难度

  • 题目描述:

实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。

调用 next() 将返回二叉搜索树中的下一个最小的数。

注意: next()hasNext() 操作的时间复杂度是O(1),并使用 O(h) 内存,其中 是树的高度。

思路分析

求解关键:

参考解答

参考解答1

import java.util.Stack;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

public class BSTIterator {

    private Stack<TreeNode> stack;

    public BSTIterator(TreeNode root) {
        stack = new Stack<>();
        TreeNode p = root;
        while (p != null) {
            stack.push(p);
            p = p.left;
        }
    }

    /**
     * @return whether we have a next smallest number
     */
    public boolean hasNext() {
        return !stack.empty();
    }

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

    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);

        node2.left = node1;
        node2.right = node5;
        node5.left = node4;
        node4.left = node3;

        BSTIterator bstIterator = new BSTIterator(node2);
        while (bstIterator.hasNext()){
            System.out.println(bstIterator.next());
        }
    }
}

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = new BSTIterator(root);
 * while (i.hasNext()) v[f()] = i.next();
 */

本篇文章的地址为 https://liweiwei1419.github.io/leetcode-solution/leetcode-0173-binary-search-tree-iterator ,如果我的题解有错误,或者您有更好的解法,欢迎您告诉我 liweiwei1419@gmail.com