gpt4 book ai didi

algorithm - 二叉树到DLL转换的时间复杂度

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:18:33 25 4
gpt4 key购买 nike

我正在研究一种将二叉树转换为双向链接列表 (DLL) 的算法。

1. If left subtree exists, process the left subtree
…..1.a) Recursively convert the left subtree to DLL.
…..1.b) Then find inorder predecessor of root in left subtree (inorder predecessor is rightmost node in left subtree).
…..1.c) Make inorder predecessor as previous of root and root as next of inorder predecessor.
2. If right subtree exists, process the right subtree (Below 3 steps are similar to left subtree).
…..2.a) Recursively convert the right subtree to DLL.
…..2.b) Then find inorder successor of root in right subtree (inorder successor is leftmost node in right subtree).
…..2.c) Make inorder successor as next of root and root as previous of inorder successor.
3. Find the leftmost node and return it (the leftmost node is always head of converted DLL).

这个算法的时间复杂度是多少?

这是程序的链接 http://www.geeksforgeeks.org/in-place-convert-a-given-binary-tree-to-doubly-linked-list/

最佳答案

首先我们可以看到,所有节点都以其后代的 root 角色被访问了一次。除了在步骤 1.b2.b 中执行的循环以及已完成的工作之外,为这样的根所做的所有工作都是不变的对于后代节点递归。

我们可以说该算法在 O(n) + O(f(n)) 中运行,其中 f 仍需要定义,但第一项 < strong>O(n) 考虑了所有节点在除那些循环之外的所有步骤上花费的时间。

由于我最初的回答是错误的,我现在进入一些(可能太多)细节以获得正确的答案:

在完全平衡的树中,具有n 个节点的树的每个(子)根执行的循环迭代次数对应于该树的深度d(n) .此 d(n) 对应于(对于平衡树):log2(n+1)。如果我们将执行 left->right!=NULLright->left!=NULL 的工作算作一个工作单元(在 this code 中),那么每个节点的执行单元数是d(n)

如果我们从递归中累加这个时间,我们得到每个节点数的工作单元总数n:

f(1) = 1
f(n) = 2.f((n-1)/2) + d(n)

在表格中:

|  n | d(n)=log(n+1) | f(n) |
+----+---------------+------+
| 1 | 1 | 1 |
| 3 | 2 | 4 |
| 7 | 3 | 11 |
| 15 | 4 | 26 |
| 31 | 5 | 57 |
| .. | .. | .. |

根据公式,f(n) 列中的值对应于它上面的值加上它旁边的值的两倍。

可以算出f(n) = 2d+1-d-2 = 2n-log(n+1),在上表中表示第一列的两倍减去第二列就是第三列。

在时间复杂度表示法中,可以去掉常数项,常数因子可以设置为1,随着n的增加增长最快的项抵消任何其他项,所以我们最终得到O(n)

由于我们已经为每个节点的恒定时间设置了 O(n),因此没有任何变化。获得有序前任/后继所花费的时间不会影响总时间复杂度。

因此时间复杂度为O(n)

关于algorithm - 二叉树到DLL转换的时间复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37230220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com