173.二叉搜索树迭代器

在这里插入图片描述

思路:二叉树的递归中序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
    vector<int> v;
public:
    BSTIterator(TreeNode* root) {
        stack<TreeNode*> s;
      TreeNode* p=root;
        while(p||!s.empty())
        {
            while(p)
            {
                s.push(p);
                p=p->right;
            }
            if(!s.empty())
            {
                p=s.top();
                s.pop();
                v.push_back(p->val);
                p=p->left;
            }
        }
    }
    /** @return the next smallest number */
    int next() {
        int temp=v.back();
        v.pop_back();
        return temp;
    }
    
    /** @return whether we have a next smallest number */
    bool hasNext() {
        return !v.empty();
    }
};

在这里插入图片描述

发布了90 篇原创文章 · 获赞 7 · 访问量 2177

猜你喜欢

转载自blog.csdn.net/weixin_43784305/article/details/103018473