【问题标题】:Binary Tree Line by Line Level Order Traversal Time Complexity二叉树逐行级别顺序遍历时间复杂度
【发布时间】:2021-03-10 00:56:17
【问题描述】:

这是逐行遍历级别顺序的代码。为什么时间复杂度是 O(n) 而不是 O(n2)。

def levelOrder(root):

queue = [root]

while len(queue):
    count = len(queue)
    while count:
        current = queue.pop(0)
        print(current.data,end='\t')
        if current.left:
            queue.append(current.left)
        if current.right:
            queue.append(current.right)

        count -= 1
    print()

Code

【问题讨论】:

    标签: data-structures queue time-complexity binary-tree


    【解决方案1】:

    不,这只有 O(N*L) 复杂度,其中 N - 节点数和 L - 级别树的数量。我解释了原因:

             Assume tree has N nodes
    
             queue = [root]         | O(1)
    
             while len(queue):       | size of level tree has : O(Level)
    
             count = len(queue)     | O(1) 
    
             while count:            | it roughly depends number nodes are left after 
                                     | processing left and right sub-tree of the current 
                                     | node; O(Left sub tree nodes) + O(Right sub tree 
                                       nodes) => O(L+R) => O(N)
                        
             count -= 1             | O(1)      
    

    就算法的上限而言,它包含为 O(N * L * 1) => O(N*L),其中是 N-Number of Nodes 和 L-Number of Level,树有。

    【讨论】:

      【解决方案2】:

      我假设 O(n2) 实际上是指 O(n^2)。

      为什么要 O(n^2)?仅仅因为你有两个嵌套循环并不意味着复杂度是 O(n^2)。这完全取决于您要迭代的内容以及您在循环中执行的操作。

      如果您查看代码的执行,您会看到树中的每个节点都被插入和弹出一次,并且循环的每次迭代都是有效的(因此没有不做任何事情的迭代) .因此,迭代次数受限于 N,即树中的节点数。所以总体复杂度是 O(N)。

      【讨论】:

        猜你喜欢
        • 2015-02-16
        • 1970-01-01
        • 1970-01-01
        • 2017-08-01
        • 2014-08-28
        • 1970-01-01
        • 2015-03-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多