Friday, September 17, 2021
More

# Merge Two Binary Trees

### How to Write C Program in Ubuntu/ Linux Programmerhttp://www.improgrammer.net
We started this site to inspire young minds to motivate and encourage them towards Programming Language. In this site you will get programming tutorials, tech, programming facts, programming fun and programming blogs.

In this article, we learn how to Merge Two Binary Trees with example and two different approaches. First approach is In Java using recursion (By creating the new tree) and Second approach is In Java using stack (By storing the result in first tree).

Question :

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You 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. Otherwise, the NOT null node will be used as the node of new tree.

Example 1:

Input:
Tree 1                     Tree 2
1                          2
/ \                       / \
3   2                     1   3
/                           \   \
5                             4   7
Output:
Merged tree:
3
/ \
4   5
/ \   \
5   4   7

Note: The merging process must start from the root nodes of both trees.

`Solution`
Approach 1: In Java using recursion (By creating the new tree)
```Public class TreeTraversal{
Public TreeNode MergeTree (TreeNode t1, TreeNode t2){

if(t1==null && t2==null)return null;

int val = (t1==null?0:t1.val)+(t2==null?0:t2.val);

TreeNode newNode = new TreeNode(val);

newNode.Left=MergeTree(t1==null?null:t1.Left, t2==null?null:t2.Left ) ;
newNode.Right=MergeTree(t1==null?null:t1. Right , t2==null?null:t2. Right ) ;

return newNode;
}

}```

Complexity Analysis

• Time complexity : O(m). A total of m nodes need to be traversed. Here, m represents the minimum number of nodes from the two given trees.
• Space complexity : O(m). The depth of the recursion tree can go upto m in the case of a skewed tree. In average case, depth will be O(logm).
Optimized Code:
```/**
&nbsp;* Definition for a binary tree node.
&nbsp;* public class TreeNode {
&nbsp;* int val;
&nbsp;* TreeNode left;
&nbsp;* TreeNode right;
&nbsp;* TreeNode(int x) { val = x; }
&nbsp;* }
&nbsp;*/
public class Solution {
&nbsp; public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {

&nbsp; if(t1 == null) return t2;
&nbsp; if(t2 == null) return t1;
&nbsp; t1.val = t1.val + t2.val;
&nbsp; t1.left = mergeTrees(t1.left, t2.left);
&nbsp; t1.right = mergeTrees(t1.right, t2.right);
&nbsp; return t1;
&nbsp; }
}
```

Approach 2: In Java using stack (By storing the result in first tree)
In this approach we will take the use of stack. We will store the element on the stack as [Node of Tree1, Node of Tree2].
We will store the result in the tree 1. If the Both Tree having the node then push them onto the stack. If left child of the tree is null then store the left of the second tree onto the first tree. Do same for the right sub-tree. Do this process untill the stack is empty. After each and every iteration we will pop the elements.
```Public class TreeTraversal {
Public TreeNode MergeTree(TreeNode t1, TreeNode t2){

if(t1==null) return t2;

Stack <TreeNode[]>  stack = new stack <>();
stack.push(new TreeNode[] {t1, t2});

while(!stack.isEmpty()){
TreeNode [] t= stack.pop();

if(t==null || t==null){
continue;
}

t.val+=t.val;

if(t.left==null){
t.left=t.left;
}
else{
stack.push(new TreeNode[] {t.left, t.left});
}

if(t.right==null){
t.right=t.right;
}
else{
stack.push(new TreeNode[] {t.right, t. right });
}

}
return t1;
}
}
```

Test case :

[1,null,1]
[1,2,3]

Complexity Analysis

• Time complexity : O(n). We traverse over a total of n nodes. Here, n refers to the smaller of the number of nodes in the two trees.
• Space complexity : O(n). The depth of stack can grow up-to n in case of a skewed tree.