Program to merge two binary trees in C++

Suppose we have two binary trees and consider that when we put one of them to cover the other, some nodes of the two trees are overlapped while the others are overlapping. We have to merge them into a new binary tree. The merge rule is like that if two nodes are overlapping, then sum node values up as the new value of the merged node. Otherwise, the non-empty node will be used as the node of new tree.

So if the trees are −

Then the output will be −

To solve this, we will follow these steps −

• The method is solve(). This take two tree nodes n1 and n2. This is like
• if n1 is empty, and n2 is non-empty, then return n2, otherwise when n2 is empty, and n1 is non empty, then return n1, and when both are null, return null
• value of n1 := value of n1 + value of n2
• left of n1 := solve (left of n1, left of n2)
• right of n1 := solve (right of n1, right of n2)
• return n1

Let us see the following implementation to get better understanding −

Example

Live Demo

#include<bits/stdc++.h>
using namespace std;
class TreeNode {
public:
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int v){
val = v;
left = right = NULL;
}
};
void inord(TreeNode *root) {
if (root != NULL) {
inord(root->left);
cout << root->val << " ";
inord(root->right);
}
}
class Solution {
public:
TreeNode* solve(TreeNode* n1, TreeNode* n2) {
if(!n1 && n2)
return n2;
else if(!n2 && n1)
return n1;
else if(!n1 && !n2)
return NULL;
n1->val+=n2->val;
n1->left = solve(n1->left,n2->left);
n1->right = solve(n1->right,n2->right);
return n1;
}
};
main(){
TreeNode *root1 = new TreeNode(1);
root1->left = new TreeNode(3);
root1->right = new TreeNode(2);
root1->left->left = new TreeNode(5);
TreeNode *root2 = new TreeNode(2);
root2->left = new TreeNode(1);
root2->right = new TreeNode(3);
root2->left->right = new TreeNode(4);
root2->right->right = new TreeNode(7);
Solution ob;
TreeNode *root_res = ob.solve(root1, root2);
inord(root_res);
}

Input

TreeNode *root1 = new TreeNode(1);
root1->left = new TreeNode(3);
root1->right = new TreeNode(2);
root1->left->left = new TreeNode(5);
TreeNode *root2 = new TreeNode(2);
root2->left = new TreeNode(1);
root2->right = new TreeNode(3);
root2->left->right = new TreeNode(4);
root2->right->right = new TreeNode(7);

Output

5 4 4 3 5 7