How to merge two BST#39;s efficiently?(如何有效地合并两个 BST?)
问题描述
如何合并两棵保持BST性质的二叉搜索树?
如果我们决定从树中取出每个元素并将其插入到另一个元素中,则该方法的复杂度将是 O(n1 * log(n2)),其中
).此操作后,只有一个 BST 有 n1
是我们分裂的树的节点数(比如 T1
),n2
是另一棵树的节点数(比如 T1
>T2n1 + n2
个节点.
If we decide to take each element from a tree and insert it into the other, the complexity of this method would be O(n1 * log(n2))
, where n1
is the number of nodes of the tree (say T1
), which we have splitted, and n2
is the number of nodes of the other tree (say T2
). After this operation only one BST has n1 + n2
nodes.
我的问题是:我们能做得比 O(n1 * log(n2)) 更好吗?
My question is: can we do any better than O(n1 * log(n2))?
推荐答案
Naaff 的回答有更多细节:
Naaff's answer with a little more details:
- 将 BST 展平为排序列表是 O(N)
- 这只是对整个树的有序"迭代.
- 同时做这件事是 O(n1+n2)
- 保持指向两个列表头部的指针
- 选择较小的头部并移动其指针
- 这就是归并排序的合并方式
- 请参阅下面的代码片段以了解算法[1]
- 在我们的例子中,排序列表的大小为 n1+n2.所以 O(n1+n2)
- 结果树将是二分搜索列表的概念 BST
三步 O(n1+n2) 结果为 O(n1+n2)
Three steps of O(n1+n2) result in O(n1+n2)
对于相同数量级的 n1 和 n2,这优于 O(n1 * log(n2))
For n1 and n2 of the same order of magnitude, that's better than O(n1 * log(n2))
[1] 从排序列表中创建平衡 BST 的算法(在 Python 中):
[1] Algorithm for creating a balanced BST from a sorted list (in Python):
def create_balanced_search_tree(iterator, n): if n == 0: return None n_left = n//2 n_right = n - 1 - n_left left = create_balanced_search_tree(iterator, n_left) node = iterator.next() right = create_balanced_search_tree(iterator, n_right) return {'left': left, 'node': node, 'right': right}
这篇关于如何有效地合并两个 BST?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何有效地合并两个 BST?


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07