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:
- it may cause the final big tree not balanced any more
- What if the worst case running time is
O(h)
, whereh
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