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?


基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01