当前位置:   article > 正文

173. 二叉搜索树迭代器

二叉搜索树迭代器

173. 二叉搜索树迭代器


题目链接:173. 二叉搜索树迭代器

代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class BSTIterator {
private:
    vector<TreeNode*> m_stack;//存储节点的数组
    vector<TreeNode*>::iterator it;//vector迭代器

    //递归中序遍历得到的是一个有序序列
    void inOrder(TreeNode* root,vector<TreeNode*>& stack)
    {
        if(root==nullptr)
            return;
        
        inOrder(root->left,stack);
        stack.push_back(root);
        inOrder(root->right,stack);
    }

public:
    ~BSTIterator(){
        //我们在开始时插入了一个不存在的点,析构时手动释放掉
        if(m_stack.size()>0)
        {   
            delete m_stack[0];
            m_stack.clear();
        }
    }

    BSTIterator(TreeNode* root) {
        m_stack.push_back(new TreeNode(INT32_MAX));
        inOrder(root,m_stack);
        it=m_stack.begin();
    }
    
    int next() {
        //先自增,再取值
        if(++it!=m_stack.end())
            return (*it)->val;
        return -1;
    }
    
    bool hasNext() {
        if((it+1)==m_stack.end())
            return false;
        return true;
    }
};

/**
 * Your BSTIterator object will be instantiated and called as such:
 * BSTIterator* obj = new BSTIterator(root);
 * int param_1 = obj->next();
 * bool param_2 = obj->hasNext();
 */
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/569389
推荐阅读
相关标签
  

闽ICP备14008679号