LeetCode173—Binary Search Tree Iterator

本文介绍了一种二叉查找树(BST)迭代器的设计方法,该迭代器通过中序遍历确保每次调用next()方法都能返回树中的下一个最小值。文章详细解释了如何在初始化时进行中序遍历并将节点值存储在一个内部向量中,以便高效地实现next()和hasNext()方法。

摘要生成于 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.

分析

设计一个二叉查找树 BST 的迭代器,其中next()方法可以始终返回其最小值,而hasNext()判定是否还有下一个节点的值可供返回,也即是否遍历完了整棵树。

BST的特性就是中序遍历是升序的,因此,我在构造函数中,对BST首先中序遍历,并将结果保存在类中成员vector<int>values_中。

除此之外,类中还有两个变量,一个表示当前遍历到什么位置,一个表示BST的节点个数,也就是vector的size。那么只要当前的位置小于size,则说明BST还没有遍历完,则hasNext返回true。

class BSTIterator {

private:
    vector<int>values_;
    int currIndex_;
    int size_;

    void InorderTraverse(TreeNode * root)
    {
        if(NULL==root)
            return;
        InorderTraverse(root->left);
        values_.push_back(root->val);
        InorderTraverse(root->right);
    }
public:
    BSTIterator(TreeNode *root):currIndex_(0)
    {
        InorderTraverse(root);
        size_=values_.size();
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        return currIndex_<size_;
    }

    /** @return the next smallest number */
    int next() {
        return values_[currIndex_++];
    }
};

不过后来想了想,不从题目本身考虑,只从设计来说,应该有一些小缺陷,比如当遍历完成后应该初始化一下,否则当hasNext返回false时,迭代器就失效了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值