Binary Search Tree Iterator: O(1)时间复杂度,O(h)空间复杂度

来源:互联网 发布:vb中range对象 编辑:程序博客网 时间:2024/06/16 01:35
class BSTIterator {public:    BSTIterator(TreeNode *root) {        while (root) {            lst.push_back(root);            TreeNode *tmp = root->left;            root = root->left;        }    }    /** @return whether we have a next smallest number */    bool hasNext() {        if (!lst.empty())            return true;        else            return false;    }    /** @return the next smallest number */    int next() {                int res = lst.back()->val;        TreeNode *tmp = lst.back();        lst.pop_back();        tmp = tmp->right;        while (tmp) {            lst.push_back(tmp);            tmp = tmp->left;        }        return res;    }        list<TreeNode *> lst; };

0 0