码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 173. Binary Search Tree Iterator

时间:2015-08-05 20:29:51      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:leetcode   c++   bst   iterator   摊还分析   

中序遍历。

用栈保存的节点,始终都为该层尚未被next()访问过的最小节点,初始化为:

        for ( ; root != nullptr; root = root->left)
        {
            stk.push(root);
        }

在每次调用next移进迭代器时,意味着移出的该节点左子树为空(之前都已迭代过),所以把它的右子树的最左路径的所有节点都加入栈中。

代码:

class BSTIterator 
{
public:
    BSTIterator(TreeNode *root) 
    {
        for ( ; root != nullptr; root = root->left)
        {
            stk.push(root);
        }
    }

    /** @return whether we have a next smallest number */
    bool hasNext() 
    {
        return !stk.empty();
    }

    /** @return the next smallest number */
    int next() 
    {
        auto node = stk.top();
        int val = node->val;
        stk.pop();
        node = node->right;
        for ( ; node != nullptr; node = node->left)
        {
            stk.push(node);
        }
        return val;
    }

private:
    stack<TreeNode*> stk;
};

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */

空间复杂度

next()中,在每个节点调用for循环,压入其右子树的最左路径时,已经保证了它的左子树为空(栈中已不存在其左子树的节点)

所以栈的深度不会超过树的深度,空间复杂度为O(h)


时间复杂度

hasNext()的时间复杂度明显是O(1);

考察next(), 进行摊还分析,运算集中在next()的for循环中,注意到树的每个节点至多只会被压入到栈中一次,亦即for循环中的push至多只会被执行O(N)次,其中N为树的节点数。

所以每次next的时间复杂度为O(N) / N = O(1)


版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode 173. Binary Search Tree Iterator

标签:leetcode   c++   bst   iterator   摊还分析   

原文地址:http://blog.csdn.net/stephen_wong/article/details/47301577

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!