Merging of height balanced trees

526 Views Asked by At

$H_1$ and $H_2$ are two height balanced trees. How can they be merged such the time required for merging them is $O(\log n_1 + \log n_2)$ where $n_1$ and $n_2$ are the number of nodes in the trees $H_1$ and $H_2$ respectively.

Every node of both the trees will store the height of sub-tree rooted at it.

Every element of $H_1$ is smaller than that of $H_2$.

One way of doing this will be as $H_1$ has all values less than $H_2$ then the entire tree $H_1$ can be made the child of the leftmost(smallest) node of $H_2$. Finding the leftmost (smallest) value will require $O(\log n_2)$ . Next rotations can be carried out on the newly constructed tree. But I cannot calculate how much time these rotations will take.

Is my approach towards solving the problem correct? If not , do point out my mistake....Thank you all in advance

1

There are 1 best solutions below

3
On BEST ANSWER

Basically what you want to look at are AVL Trees (self balancing binary trees) [wiki:AVL_Tree] to see the algorithm. Given that all elements of $H_1$ are smaller than those of $H_2$ the trees can be combined as is and only require a re-balancing step.

The time required for a rotation is kind of abstract and requires knowledge about how they are stored, from a computer science perspective this is usually done by pointers. So a rotation just switches over pointers. This is done in constant time depending on the type of tree (number of child nodes). In terms of $O$ notation it won't change anything, since it is a constant factor.