# Merge Two Balanced Binary Search Trees

In this tutorial we will learn how we can merge two balanced binary search trees.

Suppose two balanced binary search trees are given, for example, the AVL or the Red-Black Tree. Create a function that combines the two balanced BSTs provided it into balanced binary search tree. Let the first tree have m elements and the second tree have n elements. Our merge function must be O(m+n) time.

The sizes of trees are assumed to be given as input in the following solutions. We can determine the size if it is not specified by traversing the tree.

### Method 1 (Insert first tree elements into second tree):

Insert all of the first BST's elements, one by one, into the second BST. Trying to insert an element into a self-balancing BST requires Logn time (See this), in which n is the BST's size. As a result, the time complexity of this procedure is Log(n) + Log(n+1)... Log(m+n-1). This expression's value will vary between mLogn and mLog(m+n-1). As an optimization, we can select the smaller tree as the first tree.

### Method 2 (Merge Inorder Traversals):

• Perform an inorder traversal of the first tree and save the results in one temp array arr1[]. This process requires O(m) time.
• Perform an inorder traversal of the second tree and save the results in another temporary array arr2[]. This procedure takes O(n) time.
• The arrays that were formed in steps 1 and 2 are sorted arrays. Merge the two sorted arrays into a single m + n array. This procedure takes O(m+n) time.
• Using the technique described in this post, create a balanced tree from the merged array. This procedure takes O(m+n) time.

This method's time complexity is O(m+n), which is better than method 1. Even when the input BSTs are not balanced, this process requires O(m+n) time.

This method's implementation is shown below.

C++ Program:

Output:

```Following is Inorder traversal of the merged tree
10 30 60 90 100 110 130 400
```

C Program:

Output:

```Following is inorder1 traversal of the merged tree
10 30 60 90 100 110 130 400
```

### Method 3 (DLL-Based In-Place Merge):

• To merge trees in place, we can utilize a Doubly Linked List. The steps are as follows.
• In place, convert the two Binary Search Trees into a doubly linked list (Refer to this post for this step).
• Combine two sorted Linked Lists.
• Generate a Balanced Binary Search Tree using the merged list from step 2. (For more information on this step)

This method's time complexity is also O(m+n), and it performs conversion in place.

C++ Program:

Output:

```The merged data is traversed tree in order as shown below
10 30 60 90 100 110 130 400
```

The time complexity is O(N + M). where N and M are the node counts in the given trees

Auxiliary Space: O(1), because there is always extra space.