algorithm - 寻找二叉树最大深度时的最坏情况

标签 algorithm data-structures tree time-complexity binary-tree

这是求二叉树最大深度的伪代码:

 maxDepth(Node N)

1. If Nodes is leaf node then return 0

2. Else

     (a) Get the max depth of left subtree recursively  i.e., 

          call maxDepth( N->left-subtree)

     (a) Get the max depth of right subtree recursively  i.e., 

          call maxDepth( N->right-subtree)

     (c) Get the max of max depths of left and right 

          subtrees and add 1 to it for the current node.

         max_depth = max(max dept of left subtree,  
                             max depth of right subtree) 
                             + 1
     (d) Return max_depth

对于该算法的最坏情况的思考,我真的很困惑。 该伪代码的复杂度为 O(n)。该算法最坏的情况是什么?为什么?

最佳答案

正如您在问题中指出的以及其他人在评论中指出的那样,您的算法的运行时复杂度是 O(n)。它总是访问所有节点。

然而,空间复杂度是不同的。递归深度取决于树的深度。如果树是完美平衡的,则递归深度为 O(log n)。如果树是退化的——也就是说,每个节点只有一个子节点——那么递归深度和空间复杂度也是 O(n)。

这有很大的不同。想象一棵有 100 万个节点的树。如果是平衡的,空间需求将约为 20 个堆栈帧。如果树严重不平衡,则空间需求接近 100 万个堆栈帧。

那么,你的问题的答案是,运行时复杂度是 O(n),平均情况下(合理平衡的树)空间复杂度是 O(log n),最坏情况下是 O(n) .

关于algorithm - 寻找二叉树最大深度时的最坏情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46324204/

相关文章:

algorithm - Lua 创建的快速排序无法正常工作

C++:链表表示

algorithm - 从 PreOrder 构建二叉搜索树

algorithm - 如何设计一种允许在O(1)时间内搜索,插入和删除整数X的数据结构

css - 用线将 child 连接到垫树中的 parent

java - 如何评估通过链表或数组列表实现的二叉树的性能?

algorithm - Perl 在计算阶乘 N 的递归实现中在哪里保存中间结果?

c++ - 第 N 个四面体数 mod m?

algorithm - 有哪些增量构建无顺序约束的平衡二叉树的算法?

javascript - XUL。 Tree.为什么子项会掉落?