合并二进制搜索树

时间:2014-12-30 11:22:32

标签: algorithm merge binary-search-tree

我正在寻找一种合并两个BST的有效方法,因为知道第一棵树中的元素都低于第二棵树中的元素。 我看到了一些合并方法但没有该功能,我认为这应该简化算法。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果树木不平衡,或者结果不平衡,那很容易:

without loss of generality - let the first BST be smaller (in size) than the second.
1. Find the highest element in the first BST - this is done by following the right son while it is still available. Let the value be x, and the node be v
2. Remove this item (v) from the first tree
3. Create a new Root with value x, let this new root be r
4. set r.left = tree1.root, r.right = tree2.root

(*)如果第一个BST的大小大于第二个BST,只需重复查找v作为第二个树中最小节点的过程。

(*)复杂性是O(min{|T1|,|T2|})最坏的情况(如果树非常不平衡,找到最高元素),O(log(min{|T1|,|T2|}))平均情况 - 如果树相对平衡。

相关问题