Leetcode173. 二叉搜索树迭代器

强颜欢笑 提交于 2019-12-06 20:00:29

空间复杂度O(h)而不是O(n),因此不能直接在初始化函数中做中序遍历将结果存储到数组中。
next()和hasNext()时间复杂度为O(1)
首先本题很容易想到用二叉树的中序遍历去解决,外加注意点1.我们得到思路:仅仅将中序遍历最小值之前的节点压入栈中,当next时我们将栈顶元素取出即为最小值返回,当然在此之前需要将下一个最小值找到,并将路径上的所有节点压入栈中以供使用,查看是否迭代到头只需判断栈是否为空即可,如下:

class BSTIterator {
private:
      stack<TreeNode*>ss;    
public:

    BSTIterator(TreeNode* root) {
      
        while(root)
        {
            while (root)
            {
                ss.push(root);
                root=root->left;
            }
        }
    }
    
    /** @return the next smallest number */
    int next() {
         TreeNode* cur=ss.top();
         int num=cur->val;
         ss.pop();
         cur=cur->right;  
        while (cur)
        {
            ss.push(cur);
            cur=cur->left;
        }
         return num;
    }
    
    /** @return whether we have a next smallest number */
    bool hasNext() {
        return !ss.empty();
        
    }
};

 

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