【问题标题】:Is the time complexity of this code snippet O(n)?这个代码片段的时间复杂度是 O(n) 吗?
【发布时间】:2015-02-18 14:09:12
【问题描述】:
struct lists * list_depth[ht];
for(int i=0; i<ht; i++)
    list_depth[i]=NULL;
insert_to_list(&list_depth[0], root);
for( int i = 1; i < ht; i++ )
{
    struct lists * temp = list_depth[i-1];
    while( temp != NULL )
    {
        if(temp->node->llink!=NULL)
            insert_to_list(&list_depth[i],temp->node->llink);
        if(temp->node->rlink!=NULL)
            insert_to_list(&list_depth[i],temp->node->rlink);
        temp = temp->link;
    }
}

sn-p 的时间复杂度是多少?由于循环是嵌套的,它是否具有 n^2 复杂度? 这是一个在二叉树的每个深度创建元素列表的程序。 我认为是 O(n)。我对吗? [N为元素个数]

【问题讨论】:

  • 为什么你认为它是 O(n)?

标签: c complexity-theory loops binary-tree linked-list


【解决方案1】:

不,这是 O(n * log(n)),因为您正在遍历树的长度,即 O(log(n)),n 次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-22
    • 2023-04-07
    • 2015-06-14
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    • 2015-01-06
    • 2015-03-31
    相关资源
    最近更新 更多