'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?
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), wherehis 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
Solution 1:[1]
I'm going to define:
h_A= max height ofAh_B= max height ofBh = 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:
- Recursively traverse down the right of
A, and the left ofB. - Stop traversing when you get to either
max(A)ormin(B). - One of three things is possible:
- You got to
max(A). In this case, setmax(A).right = B - You got to
min(B). In this case, setmin(B).left = A - You got to
max(A)andmin(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).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
