[英]algorithm - How to concatenate two binary search tree efficiently?
I am not asking how to merge two binary search trees, as this question did How to merge two BST's efficiently? 我不是问如何合并两个二叉搜索树,因为这个问题如何有效地合并两个BST?
I am really asking how to concatenate two trees. 我真的在问如何连接两棵树。 So if tree A's all nodes are smaller than any node of tree B, we can concatenate two trees.
因此,如果树A的所有节点都小于树B的任何节点,我们可以连接两棵树。 But how do I do it efficiently?
但我该如何有效地做到这一点?
My idea is to find tree B's minimum, and then let tree A be the left child of minimum(tree B). 我的想法是找到树B的最小值,然后让树A成为最小的左子(树B)。
This is simple enough and the time is O(height of B)
. 这很简单,时间是
O(height of B)
。
But I guess this solution has some problems: 但我想这个解决方案有一些问题:
O(h)
, where h
is the max height of the two tree? O(h)
,其中h
是两棵树的最大高度怎么办? Actually, The book " Algorithm Design Manual " has this excise. 实际上,“ 算法设计手册 ”这本书有这个消费税。 Is my simple solution enough for this exercise?
我的简单解决方案是否足以进行此练习?
A concatenate operation takes two sets S1 and S2, where every key in S1 is smaller than any key in S2, and merges them together.
连接操作需要两组S1和S2,其中S1中的每个键都小于S2中的任何键,并将它们合并在一起。 Give an algorithm to concatenate two binary search trees into one binary search tree .
给出一种算法将两个二叉搜索树连接成一个二叉搜索树 。 The worst-case running time should be O(h), where h is the maximal height of the two trees.
最坏情况下的运行时间应为O(h),其中h是两棵树的最大高度。
Thanks 谢谢
Let A be the smaller set. 设A是较小的集合。 Assume x = maximum_element(A) and y = minimum_element(B).
假设x = maximum_element(A)和y = minimum_element(B)。
We know x < y. 我们知道x <y。 take a node with key value equal to
z = (x+y)/2
and make A its left subtree and B its right subtree. 取一个键值等于
z = (x+y)/2
的节点,使A为左子树,B为右子树。 remove the added node(with key z
) from this BST. 从此BST中删除添加的节点(使用密钥
z
)。
I'm going to define: 我要定义:
h_A
= max height of A
h_A
= A
最大高度 h_B
= max height of B
h_B
= B
最大高度 h = min(h_A, h_B)
Your solution's worst case running time is O(h_B)
, which happens when the depth of min(B)
is h_B
. 您的解决方案的最坏情况运行时间是
O(h_B)
,这在min(B)
的深度为h_B
。
The question asked for a O(h)
worst case. 这个问题要求
O(h)
最坏的情况。 A O(h)
solution is preferable, since if h_B
is much larger than h_A
, we'd be better off attaching B
to the right child of max(A)
than your current solution, which attaches A
to the left child of min(B)
. O(h)
解决方案是优选的,因为如果h_B
远大于h_A
,我们最好将B
附加到max(A)
的右子h_A
不是当前解决方案,它将A
附加到min(B)
的左子min(B)
。
Here's how to do that: 以下是如何做到这一点:
A
, and the left of B
. A
的右侧和B
的左侧。 max(A)
or min(B)
. max(A)
或min(B)
max(A)
. max(A)
。 In this case, set max(A).right = B
max(A).right = B
min(B)
. min(B)
。 In this case, set min(B).left = A
min(B).left = A
max(A)
and min(B)
. max(A)
和 min(B)
。 In this case, do either of the above options. At most we traversed h_A
or h_B
steps, whichever is smaller. 最多我们遍历
h_A
或h_B
步骤,以较小者为准。 That is, h
steps. 也就是说,
h
步骤。 Attaching one tree to an element is constant. 将一棵树附加到元素是不变的。 Thus the running time is O(h).
因此运行时间为O(h)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.