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 them into one single AVL tree? I've searched everywhere but haven't found anything useful.
Given two binary trees. We need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node.
Solution Steps Perform inorder traversal of tree1 and store each node's value in arr1. Perform inorder traversal of tree2 and store each node's value in arr2. Combine arr1 and arr2 using merge function of merge sort to create result array. Return result array.
A balanced tree may have different order based on the order of operations made in order to get to it. Also, there are multiple ways to do a self balancing tree (Red-Black, AVL, Splay) - all result (usually) in different trees. Both are valid AVL trees with the same elements, but as you can see - the form is not unique.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With