Binary Search Tree Iterator 设计一个二分搜索树的迭代器

在调用next()的时候,返回下次个最小的值。调用hasNext() 要返回还有没有这样的数。

时间复杂度要保证在O(1), 空间复杂度要在O(h), h是树的高度。


一个很直观的想法就是,要获得二分搜索的从小到大的序列,只要对树进行中序遍历就可得。

中序遍历后,就得到从小到大的序列了,每次调用next,就返回index++下的值。


这里有的一个限制就是空间复杂度,前面讲的解法的空间复杂度在O(n)。


所以,在这里要做的一个就是讲中序遍历拆解开。

当你需要的时候,再进行相应的后续遍历,返回当前的最小结果。

这样可以节约时间,不需要数组储存所有的遍历结果了。


代码:

public class BSTIterator {
    Stack<TreeNode> store;

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

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

    /**
     * @return the next smallest number
     */
    public int next() {
        TreeNode cur = store.pop();
        int value = cur.val;
        if (cur.right != null) {
            cur = cur.right;// let cur.right be the current node
            store.push(cur);
            cur = cur.left;
            while (cur != null) {
                store.push(cur);
                cur = cur.left;
            }
        }
        return value;
    }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值