Reputation: 25812
I am not asking how to merge two binary search trees, as this question did How to merge two BST's efficiently?
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. 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).
This is simple enough and the time is O(height of B)
.
But I guess this solution has some problems:
O(h)
, where h
is the max height of the two tree?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. 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.
Thanks
Upvotes: 6
Views: 4104
Reputation:
I'm going to define:
h_A
= max height of A
h_B
= max height of 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
.
The question asked for a O(h_B)
worst case. 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)
.
Here's how to do that:
A
, and the left of B
.max(A)
or min(B)
.max(A)
. In this case, set max(A).right = B
min(B)
. In this case, set min(B).left = A
max(A)
and min(B)
. In this case, do either of the above options.At most we traversed h_A
or h_B
steps, whichever is smaller. That is, h
steps. Attaching one tree to an element is constant. Thus the running time is O(h).
Upvotes: 4
Reputation: 1664
Let A be the smaller set. Assume x = maximum_element(A) and y = minimum_element(B).
We know 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. remove the added node(with key z
) from this BST.
Upvotes: 10