gow*_*h08 25 c++ algorithm merge binary-search-tree data-structures
如何合并两个保持BST属性的二叉搜索树?
如果我们决定从树上取每个元素,并将其插入到另一个中,这种方法的复杂性将是O(n1 * log(n2))其中n1的(比如树的节点数量T1),这是我们分裂,并且n2是节点的数量另一棵树(比如说T2).在此操作之后,只有一个BST具有n1 + n2节点.
我的问题是:我们能比O更好(n1*log(n2))吗?
yai*_*chu 26
Naaff回答了一些细节:
O(n1 + n2)的三个步骤导致O(n1 + n2)
对于相同数量级的n1和n2,它优于O(n1*log(n2))
[1]从排序列表创建平衡BST的算法(在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}
Run Code Online (Sandbox Code Playgroud)