简体   繁体   中英

Combining Binary Search Trees

the problem I am having trouble with is as follows.

Suppose that you have two different binary search trees, A and B, and you somehow know that the largest element in A is less than the smallest element in B. Suppose also that height(A) < height(B). Give an algorithm for destructively creating a binary search tree that will contain all the elements in A ∪ B and that runs in time O(height(A)).

So since the largest element in A is less than the smallest in B, that means every element in A is smaller than every element in B. In the new tree, the left hand side should be tree A and the right hand side should be tree B. But how do you do the merge programatically in time O(height(A))? Won't you need to loop through B as well? (which would make it O(height(A)+height(B))

As the problem is stated currently, you could just append the root of B tree as a right child of the largest element (which is the rightmost leaf) of A tree.

The complexity would be O(height(A)) - to find the leaf.

In the new tree, the left hand side should be tree A and the right hand side should be tree B.

Then what would the element at the root node be?

But how do you do the merge programatically in time O(height(A))?

If you were right, then you could do it in O(1): node(X, A, B) (pseudocode for creating a node with element X, left subtree A, and right subtree B).

Won't you need to loop through B as well? (which would make it O(height(A)+height(B))

If by "loop through B" you mean visiting all elements, then that would take even longer. In a balanced search tree, height(B) is proportional to log(size(B)) .


What you can do instead is walk down the rightmost branch of A (this takes O(height(A)) steps). Once you've found the end, insert B there (by assigning to node.right , in O(1) ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM