LeetCode-173: 二叉搜索树迭代器

First. Problem’s Description

Second. Problem’s Solution

BST has a non-decreasing inorder-traversing series. We can use a list to store the nodes and where we call next(), we delete the beginning node in the list.

Three. Code For Solution

class BSTIterator {
   
private:
    list<TreeNode*> lst;
public:
    BSTIterator(TreeNode* root) {
   
        if(root){
   
            TreeNode* p = root;
            stack<TreeNode*> s;
            while(!s.empty() || p){
   
                while(p){
   
                    s.push(p);
                    p = p->left;
                }
                if(!s.empty()){
   
                    p = s.top();
                    s.pop();
                    lst.push_back(p);
                    p = p->right;
                }
            }
        }
    }
    
    /** @return the next smallest number */
    int next() {
   
        auto ret = *(lst.begin());
        lst.pop_front();
        return ret->val;
    }
    
    /** @return whether we have a next smallest number */
    bool hasNext() {
   
        return lst.size() > 0;
    }
};

Four. Processing Results

全部评论

相关推荐

是正式编吗?稳定吗?工资待遇怎么样?转正可以转到腾讯总部吗?
Java抽象带篮子:不是,不稳定,一般,不行
投递腾讯云智研发等公司8个岗位 >
点赞 评论 收藏
分享
05-30 12:03
山西大学 C++
offer来了我跪着接:不是骗子,等到测评那一步就知道为啥这么高工资了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务