binary-search-tree-iterator

来源:互联网 发布:我知你忌讳是什么意思 编辑:程序博客网 时间:2024/06/07 23:57

https://leetcode.com/problems/binary-search-tree-iterator/
利用非递归 中序遍历的思想

class BSTIterator {private:    stack<TreeNode*> s;public:    BSTIterator(TreeNode *root) {        while (!s.empty())            s.pop();        while (root)        {            s.push(root);            root = root->left;        }    }    /** @return whether we have a next smallest number */    bool hasNext() {        return !s.empty();    }    /** @return the next smallest number */    int next() {        TreeNode *temp;        int minvalue;        temp = s.top();        s.pop();        minvalue = temp->val;        temp = temp->right;        while (temp)        {            s.push(temp);            temp = temp->left;        }        return minvalue;    }};
1 0
原创粉丝点击