二叉搜索树迭代器(栈)

ε祈祈猫儿з 提交于 2020-03-08 06:19:14

题目:https://leetcode-cn.com/problems/binary-search-tree-iterator/

/**
 * 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 {
public:
    /*
    *实现一个二叉搜索树迭代器。你将使用二叉搜索树的
    *根节点初始化迭代器。调用 next() 将返回二叉搜索
    *树中的下一个最小的数。
    */
    stack<TreeNode*>st;
    BSTIterator(TreeNode* root) {
        while(root){
            st.push(root);
            root=root->left;
        }
    }
    int next() {
        TreeNode* p=st.top();
        st.pop();
        int ans=p->val;
        p=p->right;
        while(p){
            st.push(p);
            p=p->left;
        }
        return ans;
    }
    bool hasNext() {
        return !st.empty();
    }
};

/**
 * 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();
 */
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!