LeetCode 173. Binary Search Tree 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)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值