LeetCode173——二叉搜索树迭代器

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/binary-search-tree-iterator/description/

题目描述:

知识点:二叉搜索树、栈

思路:中序遍历的分段实现

本题的中文翻译出错,原英文如下:

next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

正确的翻译应该是next()和hashNext()的平均时间复杂度是O(1),这说明有时候我们的时间复杂度可以达到O(n)或O(h),其中n为树中的节点个数。

一开始我的思路是,先中序遍历该树,将结果保存在一个List集合里,再输出即可,但这样无法满足O(h)的内存要求。

联想LeetCode094——二叉树的中序遍历中的思路三和思路四,我们其实可以实现分段中序遍历。

在构造函数中,我们的cur指针一直往左走,寻找到最小值。

而对于next()函数,弹出栈顶元素,该元素的val值即next需返回的值,但我们还需要更新维护我们的栈。如果栈顶元素的右孩子不为null,我们需要对其右子树部分进行和构造函数中同样的入栈操作。

以上两步本质上就是LeetCode094——二叉树的中序遍历中思路三和思路四的分段实现。

next()函数的平均时间复杂度是O(1)。

hashNext()函数的时间复杂度是O(1)。

空间复杂度是O(h)。

JAVA代码:

public class BSTIterator {
    private LinkedList<TreeNode> stack = new LinkedList<>();
    public BSTIterator(TreeNode root) {
        TreeNode cur = root;
        pushToStack(cur);
    }
    public int next() {
        TreeNode node = stack.pop();
        TreeNode cur = node;
        if(null != cur.right){
            cur = cur.right;
            pushToStack(cur);
        }
        return node.val;
    }
    public boolean hasNext() {
        return !stack.isEmpty();
    }
    private void pushToStack(TreeNode treeNode){
        TreeNode cur = treeNode;
        while(cur != null){
            stack.push(cur);
            if(cur.left != null)
                cur = cur.left;
            else
                break;
        }
    }
}

LeetCode解题报告:

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值