Assume that I have two AVL trees and that each element from the first tree is smaller then any element from the second tree. What is the most efficient way to concatenate th
One ultra simple solution (that works without any assumptions in the relations between the trees) is this:
Both steps are O(n). The major issue with it is that it takes O(n) extra space.
I suspect that you'll just have to walk one tree (hopefully the smaller) and individually add each of it's elements to the other tree. The AVL insert/delete operations are not designed to handle adding a whole subtree at a time.
Assuming you may destroy the input trees:
Thus, the entire operation can be performed in O(log n).
Edit: On second thought, it is easier to reason about the rotations in the following algorithm. It is also quite likely faster:
left
tree (rotating and adjusting its computed height if necessary). Let n
be that element. O(log n)left
. Let r
be that node. O(log n)replace that node with a new node with value n, and subtrees left
and r
. O(1)
By construction, the new node is AVL-balanced, and its subtree 1 taller than r
.
increment its parent's balance accordingly. O(1)
The best solution I read to this problem can be found here. Is very close to meriton's answer if you correct this issue:
In the third step of the algorithm navigates left until you reach the node whose sub tree has the same height as the left tree. This is not always possible, (see counterexample image). The right way to do this step is two find for a subtree with height h
or h+1
where h
is the height of the left tree