[Java]leetcode173 Binary Search Tree Iterator

该博客介绍如何在Java中实现一个二叉搜索树的迭代器,满足hasNext和next操作,这两个操作在平均情况下应具有O(1)的时间复杂度,且使用O(h)的空间,其中h为树的高度。内容涉及二叉树中序遍历策略来找到未访问的最小值。
摘要由CSDN通过智能技术生成

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling next() will return the next smallest number in the BST.

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

题意:写一个二叉查找树的迭代器,实现hasNext()和next()的功能。next()每次返回二叉树中未访问的最小值。要求的平均时间复杂度是O(1)和空间复杂度是O(h)。

解题思路:next()每次返回二叉树中未访问的最小值。也就是将二叉树中序遍历,并将对应值输出。这里面注意的是空间和时间的复杂度。

public class BSTIterator {//将中序遍历的功能嵌查在整个程序中
    TreeNode current;
    Stack<TreeNode> stack;
    public BSTIterator(TreeNode root) {
        current=root;
        stack=new Stack<TreeNode>();
        while(current!=null)//因为只可能是左节点才是最小值,将所有左子树节点入栈,保证空间复杂度是O(h)
        {
            stack.push(current);
            current=current.left;
        }
    }
    /** @return whether we have a next smallest number */
    public boolean hasNext() {
     return !stack.isEmpty();
    }
    /** @return the next smallest number */
    public int next() {
      current=stack.pop();
      int res=current.val;//这一步已经得到最小值
      current=current.right;//但要考虑到右子树的遍历
      while(current!=null)
       {
         stack.push(current);
         current=current.left;
       }
       return res;
      }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值