Given the roots of two binary trees. The task is to merge the two trees. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the non-null node will be used as the node of the new tree.
Note: The merging process must start from the root nodes of both trees.
Examples:
Input:
Output:
Explanation: root of the both the trees overlap, they sum up to give 2.
The idea is to traverse both the given trees in preorderfashion. At each step, check whether the current node exists (NOT null) for both of the trees. If so, add the values and update in the first tree, else return the non-null node(if it exists). Now recursively apply this operation for left and right subtree. At the end, the first tree will represent the merged binary tree.
C++
// C++ program to Merge Two Binary Trees#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Function to print node values in inorder.voidinorder(Node*node){if(node==nullptr)return;// Recur on left childinorder(node->left);// Print the data of current nodecout<<node->data<<" ";// Recur on right childinorder(node->right);}// Function to merge binary treesNode*mergeTrees(Node*t1,Node*t2){// if either of the node is null// return the other node.if(t1==nullptr)returnt2;if(t2==nullptr)returnt1;//If both the nodes are not NULL// add the value of second to first node.t1->data+=t2->data;// recur on left subtree and// update the left child of first node.t1->left=mergeTrees(t1->left,t2->left);// recur on right subtree and// update the right child of first node.t1->right=mergeTrees(t1->right,t2->right);// return merged tree.returnt1;}intmain(){// construct the first Binary Tree// 1// / \ // 2 3// / \ \ // 4 5 6 Node*root1=newNode(1);root1->left=newNode(2);root1->right=newNode(3);root1->left->left=newNode(4);root1->left->right=newNode(5);root1->right->right=newNode(6);// construct the second Binary Tree//// 4// / \ // 1 7// / / \ // 3 2 6Node*root2=newNode(4);root2->left=newNode(1);root2->right=newNode(7);root2->left->left=newNode(3);root2->right->left=newNode(2);root2->right->right=newNode(6);Node*root=mergeTrees(root1,root2);inorder(root);return0;}
C
// C program to Merge Two Binary Trees#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left,*right;};// Function to print node values in inorder.voidinorder(structNode*node){if(node==NULL)return;// Recur on left childinorder(node->left);// Print the data of current nodeprintf("%d ",node->data);// Recur on right childinorder(node->right);}// Function to merge binary treesstructNode*mergeTrees(structNode*t1,structNode*t2){// if either of the node is null// return the other node.if(t1==NULL)returnt2;if(t2==NULL)returnt1;// If both the nodes are not NULL// add the value of second to first node.t1->data+=t2->data;// recur on left subtree and// update the left child of first node.t1->left=mergeTrees(t1->left,t2->left);// recur on right subtree and// update the right child of first node.t1->right=mergeTrees(t1->right,t2->right);// return merged tree.returnt1;}structNode*createnode(intdata){structNode*newnode=(structNode*)malloc(sizeof(structNode));newnode->data=data;newnode->left=newnode->right=NULL;returnnewnode;}intmain(){// construct the first Binary Tree// 1// / \ // 2 3// / \ \ // 4 5 6 structNode*root1=createnode(1);root1->left=createnode(2);root1->right=createnode(3);root1->left->left=createnode(4);root1->left->right=createnode(5);root1->right->right=createnode(6);// construct the second Binary Tree// 4// / \ // 1 7// / / \ // 3 2 6structNode*root2=createnode(4);root2->left=createnode(1);root2->right=createnode(7);root2->left->left=createnode(3);root2->right->left=createnode(2);root2->right->right=createnode(6);structNode*root=mergeTrees(root1,root2);inorder(root);return0;}
Java
// Java program to Merge Two Binary TreesclassNode{intdata;Nodeleft,right;Node(intvalue){data=value;left=right=null;}}classGfG{// Function to print node values in inorderstaticvoidinorder(Nodenode){if(node==null)return;// Recur on left childinorder(node.left);// Print the data of current nodeSystem.out.print(node.data+" ");// Recur on right childinorder(node.right);}// Function to merge binary treesstaticNodemergeTrees(Nodet1,Nodet2){// if either of the node is null// return the other nodeif(t1==null)returnt2;if(t2==null)returnt1;// If both the nodes are not NULL// add the value of second to first nodet1.data+=t2.data;// recur on left subtree and// update the left child of first nodet1.left=mergeTrees(t1.left,t2.left);// recur on right subtree and// update the right child of first nodet1.right=mergeTrees(t1.right,t2.right);// return merged treereturnt1;}publicstaticvoidmain(String[]args){// construct the first Binary Tree// 1// / \// 2 3// / \ \// 4 5 6Noderoot1=newNode(1);root1.left=newNode(2);root1.right=newNode(3);root1.left.left=newNode(4);root1.left.right=newNode(5);root1.right.right=newNode(6);// construct the second Binary Tree// 4// / \// 1 7// / / \// 3 2 6 Noderoot2=newNode(4);root2.left=newNode(1);root2.right=newNode(7);root2.left.left=newNode(3);root2.right.left=newNode(2);root2.right.right=newNode(6);Noderoot=mergeTrees(root1,root2);inorder(root);}}
Python
# Python program to Merge Two Binary TreesclassNode:def__init__(self,data):self.data=dataself.left=self.right=None# Function to print node values in inorderdefinorder(node):ifnodeisNone:return# Recur on left childinorder(node.left)# Print the data of current nodeprint(node.data,end=" ")# Recur on right childinorder(node.right)# Function to merge binary treesdefmergeTrees(t1,t2):# if either of the node is null# return the other nodeift1isNone:returnt2ift2isNone:returnt1# If both the nodes are not NULL# add the value of second to first nodet1.data+=t2.data# recur on left subtree and# update the left child of first nodet1.left=mergeTrees(t1.left,t2.left)# recur on right subtree and# update the right child of first nodet1.right=mergeTrees(t1.right,t2.right)# return merged treereturnt1if__name__=="__main__":# construct the first Binary Tree# 1# / \# 2 3# / \ \# 4 5 6root1=Node(1)root1.left=Node(2)root1.right=Node(3)root1.left.left=Node(4)root1.left.right=Node(5)root1.right.right=Node(6)# construct the second Binary Tree## 4# / \# 1 7# / / \# 3 2 6root2=Node(4)root2.left=Node(1)root2.right=Node(7)root2.left.left=Node(3)root2.right.left=Node(2)root2.right.right=Node(6)root=mergeTrees(root1,root2)inorder(root)
C#
// C# program to Merge Two Binary TreesusingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intdata){this.data=data;this.left=null;this.right=null;}}classGfG{// Function to print node values in inorderstaticvoidinorder(Nodenode){if(node==null)return;// Recur on left childinorder(node.left);// Print the data of current nodeConsole.Write(node.data+" ");// Recur on right childinorder(node.right);}// Function to merge binary treesstaticNodemergeTrees(Nodet1,Nodet2){// if either of the node is null// return the other nodeif(t1==null)returnt2;if(t2==null)returnt1;// If both the nodes are not NULL// add the value of second to first nodet1.data+=t2.data;// recur on left subtree and// update the left child of first nodet1.left=mergeTrees(t1.left,t2.left);// recur on right subtree and// update the right child of first nodet1.right=mergeTrees(t1.right,t2.right);// return merged treereturnt1;}staticvoidMain(string[]args){// construct the first Binary Tree// 1// / \// 2 3// / \ \// 4 5 6Noderoot1=newNode(1);root1.left=newNode(2);root1.right=newNode(3);root1.left.left=newNode(4);root1.left.right=newNode(5);root1.right.right=newNode(6);// construct the second Binary Tree//// 4// / \// 1 7// / / \// 3 2 6Noderoot2=newNode(4);root2.left=newNode(1);root2.right=newNode(7);root2.left.left=newNode(3);root2.right.left=newNode(2);root2.right.right=newNode(6);Noderoot=mergeTrees(root1,root2);inorder(root);}}
JavaScript
// Javascript program to Merge Two Binary TreesclassNode{constructor(value){this.data=value;this.left=null;this.right=null;}}// Function to print the inorder traversal of the tree.functioninorder(node){if(node===null)return;// Recur on left childinorder(node.left);// Print the value of the current nodeconsole.log(node.data);// Recur on right childinorder(node.right);}// Function to merge two binary treesfunctionmergeTrees(t1,t2){// If either of the nodes is null, return the other nodeif(t1===null)returnt2;if(t2===null)returnt1;// If both nodes are not null, add the value of t2's// node to t1's nodet1.data+=t2.data;// Recursively merge left and right childrent1.left=mergeTrees(t1.left,t2.left);t1.right=mergeTrees(t1.right,t2.right);// Return the merged treereturnt1;}// construct the first Binary Tree// 1// / \// 2 3// / \ \// 4 5 6letroot1=newNode(1);root1.left=newNode(2);root1.right=newNode(3);root1.left.left=newNode(4);root1.left.right=newNode(5);root1.right.right=newNode(6);// construct the second Binary Tree//// 4// / \// 1 7// / / \// 3 2 6letroot2=newNode(4);root2.left=newNode(1);root2.right=newNode(7);root2.left.left=newNode(3);root2.right.left=newNode(2);root2.right.right=newNode(6);letroot=mergeTrees(root1,root2);inorder(root);
Output
7 3 5 5 2 10 12
Using Iteration - O(n) Time and O(n) Space
The idea is to traverse both the given trees using a stack. At each step, check whether the current nodes exist (not NULL) for both of the trees. If so, add the values and update in the first tree. Otherwise, if the left child of the first tree exists, push the left children (pair) of both trees onto the stack. If not, append the left child of the second tree to the current node of the first tree. Repeat the same process for the right child pair. If both the current nodes are null, continue with the next node pair from the stack. At the end, the first tree will represent the merged binary tree.
C++
// C++ program to Merge Two Binary Trees // using iteration#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Function to perform an inorder traversal // of the binary treevoidinorder(Node*node){// Base case: if the node is null, returnif(node==nullptr)return;// Recursively traverse the left subtreeinorder(node->left);// Print the current node's datacout<<node->data<<" ";// Recursively traverse the right subtreeinorder(node->right);}// Function to merge two binary trees iteratively// using pair<Node*, Node*>Node*mergeTrees(Node*t1,Node*t2){// If the first tree is null, return the second treeif(t1==nullptr)returnt2;// If the second tree is null, return the first treeif(t2==nullptr)returnt1;// Stack to store pairs of nodes to be processedstack<pair<Node*,Node*>>s;// Initialize the stack with the root// nodes of both treess.push({t1,t2});while(!s.empty()){// Get the top pair of nodes from the stackpair<Node*,Node*>n=s.top();s.pop();// If either node is null, skip this pairif(n.first==nullptr||n.second==nullptr)continue;// Add the data of the second tree's node to // the first tree's noden.first->data+=n.second->data;// Process the left childrenif(n.first->left==nullptr)n.first->left=n.second->left;else{s.push({n.first->left,n.second->left});}// Process the right childrenif(n.first->right==nullptr)n.first->right=n.second->right;else{s.push({n.first->right,n.second->right});}}// Return the root of the merged treereturnt1;}intmain(){// Construct the first Binary Tree// 1// / \ // 2 3// / \ \ // 4 5 6Node*root1=newNode(1);root1->left=newNode(2);root1->right=newNode(3);root1->left->left=newNode(4);root1->left->right=newNode(5);root1->right->right=newNode(6);// Construct the second Binary Tree// 4// / \ // 1 7// / / \ // 3 2 6Node*root2=newNode(4);root2->left=newNode(1);root2->right=newNode(7);root2->left->left=newNode(3);root2->right->left=newNode(2);root2->right->right=newNode(6);Node*root=mergeTrees(root1,root2);inorder(root);return0;}
Java
// Java program to Merge Two Binary Trees// using iterationimportjava.util.Stack;classNodePair{Nodetree1,tree2;NodePair(Nodet1,Nodet2){tree1=t1;tree2=t2;}}classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Function to perform inorder traversal of the binary// treestaticvoidinorder(Nodenode){if(node==null){return;}inorder(node.left);System.out.print(node.data+" ");inorder(node.right);}// Function to merge two binary trees iteratively using// NodePairstaticNodemergeTrees(Nodet1,Nodet2){if(t1==null){returnt2;}if(t2==null){returnt1;}// Stack to store pairs of nodes to be processedStack<NodePair>stack=newStack<>();// Push the root nodes of both trees// onto the stackstack.push(newNodePair(t1,t2));while(!stack.isEmpty()){NodePairpair=stack.pop();Nodenode1=pair.tree1;Nodenode2=pair.tree2;if(node1==null||node2==null){continue;}// Add the data of the second tree's node to the// first tree's nodenode1.data+=node2.data;// If the left child of node1 is null, assign it// to node2's left childif(node1.left==null){node1.left=node2.left;}else{stack.push(newNodePair(node1.left,node2.left));}// If the right child of node1 is null, assign// it to node2's right childif(node1.right==null){node1.right=node2.right;}else{stack.push(newNodePair(node1.right,node2.right));}}// Return the root of the merged treereturnt1;}publicstaticvoidmain(String[]args){// Construct the first Binary Tree// 1// / \// 2 3// / \ \// 4 5 6Noderoot1=newNode(1);root1.left=newNode(2);root1.right=newNode(3);root1.left.left=newNode(4);root1.left.right=newNode(5);root1.right.right=newNode(6);// Construct the second Binary Tree// 4// / \// 1 7// / / \// 3 2 6Noderoot2=newNode(4);root2.left=newNode(1);root2.right=newNode(7);root2.left.left=newNode(3);root2.right.left=newNode(2);root2.right.right=newNode(6);NodemergedRoot=mergeTrees(root1,root2);inorder(mergedRoot);}}
Python
# Python program to Merge Two Binary Trees# using iterationclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to perform inorder traversal of the binary treedefinorder(node):# Base case: if the node is null, returnifnodeisNone:return# Recursively traverse the left subtreeinorder(node.left)# Print the current node's dataprint(node.data,end=" ")# Recursively traverse the right subtreeinorder(node.right)# Function to merge two binary trees iteratively # using tuple (node1, node2)defmergeTrees(t1,t2):# If the first tree is null, return# the second treeift1isNone:returnt2# If the second tree is null, return the first treeift2isNone:returnt1# Stack to store pairs of nodes to be processedstack=[(t1,t2)]whilestack:# Get the top pair of nodes from the stacknode1,node2=stack.pop()# If either node is null, skip this pairifnode1isNoneornode2isNone:continue# Add the data of the second tree's node to # the first tree's nodenode1.data+=node2.data# If the left child of node1 is null, assign it# to node2's left childifnode1.leftisNone:node1.left=node2.leftelse:stack.append((node1.left,node2.left))# If the right child of node1 is null, assign it# to node2's right childifnode1.rightisNone:node1.right=node2.rightelse:stack.append((node1.right,node2.right))# Return the root of the merged treereturnt1if__name__=="__main__":# Construct the first Binary Tree# 1# / \# 2 3# / \ \# 4 5 6root1=Node(1)root1.left=Node(2)root1.right=Node(3)root1.left.left=Node(4)root1.left.right=Node(5)root1.right.right=Node(6)# Construct the second Binary Tree# 4# / \# 1 7# / / \# 3 2 6root2=Node(4)root2.left=Node(1)root2.right=Node(7)root2.left.left=Node(3)root2.right.left=Node(2)root2.right.right=Node(6)merged_root=mergeTrees(root1,root2)inorder(merged_root)
C#
// C# program to Merge Two Binary Trees// using iterationusingSystem;usingSystem.Collections.Generic;publicclassNode{publicintData;publicNodeLeft,Right;publicNode(intx){Data=x;Left=Right=null;}}classGfG{// Function to perform inorder traversal of the binary// treestaticvoidInorder(Nodenode){// Base case: if the node is null, returnif(node==null)return;// Recursively traverse the left subtreeInorder(node.Left);// Print the current node's dataConsole.Write(node.Data+" ");// Recursively traverse the right subtreeInorder(node.Right);}// Function to merge two binary trees iteratively using// tuple (node1, node2)staticNodeMergeTrees(Nodet1,Nodet2){// If the first tree is null, return the// second treeif(t1==null)returnt2;// If the second tree is null, return the first treeif(t2==null)returnt1;// Stack to store pairs of nodes to be processedStack<Tuple<Node,Node>>stack=newStack<Tuple<Node,Node>>();stack.Push(newTuple<Node,Node>(t1,t2));while(stack.Count>0){// Get the top pair of nodes from the stackvarpair=stack.Pop();Nodenode1=pair.Item1;Nodenode2=pair.Item2;// If either node is null, skip this pairif(node1==null||node2==null)continue;// Add the data of the second tree's node to the// first tree's nodenode1.Data+=node2.Data;// If the left child of node1 is null, assign it// to node2's left childif(node1.Left==null)node1.Left=node2.Left;elsestack.Push(newTuple<Node,Node>(node1.Left,node2.Left));// If the right child of node1 is null, assign// it to node2's right childif(node1.Right==null)node1.Right=node2.Right;elsestack.Push(newTuple<Node,Node>(node1.Right,node2.Right));}// Return the root of the merged treereturnt1;}staticvoidMain(string[]args){// Construct the first Binary Tree// 1// / \// 2 3// / \ \// 4 5 6Noderoot1=newNode(1);root1.Left=newNode(2);root1.Right=newNode(3);root1.Left.Left=newNode(4);root1.Left.Right=newNode(5);root1.Right.Right=newNode(6);// Construct the second Binary Tree// 4// / \// 1 7// / / \// 3 2 6Noderoot2=newNode(4);root2.Left=newNode(1);root2.Right=newNode(7);root2.Left.Left=newNode(3);root2.Right.Left=newNode(2);root2.Right.Right=newNode(6);NodemergedRoot=MergeTrees(root1,root2);Inorder(mergedRoot);}}
JavaScript
// Javascript program to Merge Two Binary Trees// using iterationclassNode{constructor(x){this.data=x;this.left=this.right=null;}}// Function to perform inorder traversal of the binary treefunctioninorder(node){// Base case: if the node is null, returnif(node===null)return;// Recursively traverse the left subtreeinorder(node.left);// Print the current node's dataconsole.log(node.data+" ");// Recursively traverse the right subtreeinorder(node.right);}// Function to merge two binary trees iteratively using a// stackfunctionmergeTrees(t1,t2){// If the first tree is null, return the second treeif(t1===null)returnt2;// If the second tree is null, return the first treeif(t2===null)returnt1;// Stack to store pairs of nodes to be processedletstack=[];// Push the root nodes of both trees into the stackstack.push({tree1:t1,tree2:t2});while(stack.length>0){// Get the top pair of nodes from the stacklet{tree1,tree2}=stack.pop();// If either node is null, skip this pairif(tree1===null||tree2===null)continue;// Add the data of the second tree's node to the// first tree's nodetree1.data+=tree2.data;// If the left child of tree1 is null, assign it to// tree2's left childif(tree1.left===null)tree1.left=tree2.left;elsestack.push({tree1:tree1.left,tree2:tree2.left});// If the right child of tree1 is null, assign it to// tree2's right childif(tree1.right===null)tree1.right=tree2.right;elsestack.push({tree1:tree1.right,tree2:tree2.right});}returnt1;}// Construct the first Binary Tree// 1// / \// 2 3// / \ \// 4 5 6constroot1=newNode(1);root1.left=newNode(2);root1.right=newNode(3);root1.left.left=newNode(4);root1.left.right=newNode(5);root1.right.right=newNode(6);// Construct the second Binary Tree// 4// / \// 1 7// / / \// 3 2 6constroot2=newNode(4);root2.left=newNode(1);root2.right=newNode(7);root2.left.left=newNode(3);root2.right.left=newNode(2);root2.right.right=newNode(6);constmergedRoot=mergeTrees(root1,root2);inorder(mergedRoot);