Javatpoint Logo
Javatpoint Logo

Merge Two Binary Trees

In the following tutorial, we will understand how to merge two Binary Trees into a Single Binary Tree.

Level of Difficulty: Easy

Asked In: Adobe, Amazon, Microsoft, Hike

Important Outcome: A brilliant problem to understand problem-solving with the help of iterative and recursive pre-order traversals.

Understanding the Problem

There are two binary trees with root nodes as first_root and second_root, and we are required to write a program in order to merge these trees into a single binary tree.

In order to solve this problem, imagine placing one tree over the other to cover it. We will notice that some nodes of both trees overlap while others are not.

The rule of merging says that if two nodes overlap, then sum up the values of nodes as the new value of the merged node. Or else, the NOT null node will be utilized as the new value of the merged node.

We are required to return the root of the merged tree.

The process of merging must begin from the root nodes of both trees.

Example 1:

Input:

Output:

     Merged Tree
          8
         / \
        7   5
       / \   \
      7   2   8

Example 2:

Input:

Output:

     Merged Tree
          7
         / \
        6   8
       / \   \
      5   1   6

Understanding the Solution Approaches:

The following are some approaches that we will use to find the solution to the problem:

  1. First Solution Approach: Using Pre-order Traversal
  2. Second Solution Approach: Using Stack
  3. Third Solution Approach: Using BFS Traversal

Let us understand each of the above approaches in detail.

First Solution Approach: Using Pre-order Traversal

The main idea behind this solution approach is to visit each node of the input binary trees with the help of pre-order traversal and verify their existence in both trees. If the selected nodes in both the trees are not NULL, we will sum up their values and update the current node value in the first tree. At the end of the traversal, the first tree will be the output, i.e., the merged Binary Tree.

Steps to solve the problem

The following are some steps that we will use in order to solve this problem using the Pre-order Traversal approach:

Step 1: Firstly, we will traverse both the trees in pre-order fashion.

Step 2: We will then check if any of the trees is NULL and return the other tree's root as an output. Otherwise, we will sum up the first_root and second_root for the overlapping nodes and update the first_root's value with that resultant value.

Step 3: After that, we will recursively merge the left subtree of both trees by calling the same function and assigning it to the left node of the first_root.

Step 4: We will then recursively merge the right subtree of both trees by calling the same function and assigning it to the right node of the first_root.

Step 5: At last, we will return the root of the merged tree, i.e., first_root.

Let us now see the pseudocode for this solution.

Pseudocode of the Solution

Let us now consider the following pseudocode illustrating the same.

Pseudocode:

Analysis of Time and Space Complexity

Let the number of nodes in both trees be x and y, respectively.

So in the worst case, we will visit min(x, y) nodes recursively, performing O(1) operations with each node. Hence, the Time complexity of this approach will be O(min(x, y)).

Moreover, in the worst case, the depth of the recursive tree can go up to min(x, y) for the Skewed Tree. Hence, the Space Complexity will be O(min(x, y)).

Second Solution Approach: Iterative Pre-order Traversal Using Stack

We will now try to solve the given problem by traversing both trees iteratively in a pre-order fashion. The main objective is to merge both trees so that we will be able to track the nodes of both trees simultaneously with the help of the Stack. To achieve the goal, we will store the data in a pair of nodes in the Stack: {firstTreeNode, secondTreeNode}. Here, firstTreeNode and secondTreeNode are the nodes of the first tree and the second tree, respectively.

Steps to solve the problem

The following are some steps that we will use in order to solve this problem using Iterative Pre-order Traversal with the help of the Stack:

Step 1: We will start by creating a Stack to store the pair of nodes of both trees.

Step 2: We will push the root nodes of both trees in the Stack.

Step 3: We will run a loop until the Stack gets empty. For every iteration, we will follow a set of rules as below:

Step 3.1: We will remove a node pair from the Stack and update the corresponding node in the first tree with the sum of their values.

Step 3.2: If both current nodes are NULL, we will continue popping the next pair of nodes from the Stack.

Step 3.3: If the left child of the first tree is not NULL, we will push the left child of both the trees in the Stack.

Step 3.4: If the left child of the first tree is NULL, we will append the left child of the second tree to the current node of the first tree.

Step 3.5: We will continue the same procedure for the right child pair.

Step 4: We will, at last, return the root of the merged tree, i.e., first_root.

Let us now see the pseudocode for this solution.

Pseudocode of the Solution

Let us now consider the following pseudocode illustrating the same.

Pseudocode:

Analysis of Time and Space Complexity

Let the number of nodes in both trees be x and y, respectively.

So in the worst case, we will visit min(x, y) nodes recursively, performing O(1) operations with each node. Hence, the Time complexity of this approach will be O(min(x, y)).

Moreover, in the worst case, the size of the stack space will be min(x, y) for the Skewed Tree. Hence, the Space Complexity will be O(min(x, y)).

Third Solution Approach: Using BFS or Level Order Traversal

The main idea behind this solution approach is to merge both trees by accessing each node of the trees in the same order and adding their corresponding node's values. Thus, we can also solve this problem with the help of the Breadth First Search (BFS) or Level Order Traversal, where we will merge both trees in a level-by-level fashion.

The idea of implementation is similar to the above approach; however, we will use the Queue data structure to track the order of nodes and merge their values.

Let us now see the pseudocode for this solution.

Pseudocode of the Solution

Let us now consider the following pseudocode illustrating the same.

Pseudocode:

Analysis of Time and Space Complexity

Let the number of nodes in both trees be x and y, respectively.

So in the worst case, we will visit min(x, y) nodes recursively, performing O(1) operations with each node. Hence, the Time complexity of this approach will be O(min(x, y)).

Note:
It is recommended to transform the above pseudocodes into the favorable programming language like C, C++, Java, Python, etc. and verify all the test.

Complete Program to merge Two Binary Trees into a Single Binary Tree in C

Let us now see a complete transformation of one of the pseudocodes shown above in C programming language.

Code:

Output:

The New Merged Binary Tree is : 
7 7 2 8 8 5

Explanation:

In the above snippet of code, we have included the necessary header files like stdio.h and stdlib.h, respectively. We have then defined a structure using the struct statement within which we have defined the members like data storing the integer data type and two pointers pointing to the left and right child. We have then defined a helping function that allocates a new node with the given data and NULL left and right pointers. We have also defined a function to print the nodes of the Tree data structure in an in-order fashion. We have then defined the function to merge two Binary Trees into a Single Binary Tree using the pre-order traversal based on the concept of recurrence. Within this function, we have checked if any Tree is empty and returned another Tree. If both Trees consist of some nodes, we have then summed up their data recurring on both Trees' left and right child, storing the resultant value in the nodes of the first Tree, respectively, and returning it as a result. We have then defined the main function where we have declared the values of each node of both Trees. We have then called the mergeBinTree() function to execute the process of merging and stored the result in another tree. At last, we have called the inorder() function to print the values of the nodes of the resultant tree.

The Conclusion

In the above tutorial, we have learned different approaches to merging two Binary Trees into a Single Binary Tree.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA