LeetCode Binary Search Tree Iterator

本文详细介绍了如何实现一个二叉搜索树的迭代器,包括初始化、判断是否存在下一个元素及获取下一个元素的方法,实现中利用了递归进行先序遍历,并使用ArrayList存储遍历结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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.

例子:

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

题意:就是和上一题一样,在一棵二叉搜索树中,依次返回每个最小的值,此题就是典型的用递归来先序遍历得到结果,然后就是用一个判断是否存在下一个值,若存在,那么就直接再输出,否则就返回空。要求写两个函数,判断是否还存在的和取值的函数。

public class BSTIterator 
{
    ArrayList<Integer> list = new ArrayList<Integer>();  //全局变量非常好
    int i = 0;
    public BSTIterator(TreeNode root) 
    {
        dfs(root);
    }

    public void dfs(TreeNode root)
    {
        if(root == null)
           return;
        else
        {
            if(root.left != null)
               dfs(root.left);
            list.add(root.val);
            if(root.right != null)
               dfs(root.right);
        }
    }
    /** @return whether we have a next smallest number */
    public boolean hasNext()
    {
        int length = list.size();   //注意,这里采用判断是否这个小于list的长度
        if(i < length)
            return true;
        else 
            return false;
    }

    /** @return the next smallest number */
    public int next() 
    {
         int result = list.get(i).intValue();   //考虑返回
         i++;     //并且在这里加1
         return result;
    } 
}
此题,和之前我博客中的那题异曲同工,可以对比着看。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值