Merge Two Balanced Binary Search TreesIn 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):
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):
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. |