Merge Two Binary Trees by doing Node Sum
Last Updated :
16 Dec, 2024
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.
Input:
Output:
Using Recursion - O(n) Time and O(h) Space
The idea is to traverse both the given trees in preorder fashion. 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>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
Node(int x){
data = x;
left = right = nullptr;
}
};
// Function to print node values in inorder.
void inorder(Node * node) {
if (node == nullptr)
return;
// Recur on left child
inorder(node->left);
// Print the data of current node
cout<<node->data<<" ";
// Recur on right child
inorder(node->right);
}
// Function to merge binary trees
Node *mergeTrees(Node * t1, Node * t2) {
// if either of the node is null
// return the other node.
if (t1 == nullptr)
return t2;
if (t2 == nullptr)
return t1;
//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.
return t1;
}
int main() {
// construct the first Binary Tree
// 1
// / \
// 2 3
// / \ \
// 4 5 6
Node *root1 = new Node(1);
root1->left = new Node(2);
root1->right = new Node(3);
root1->left->left = new Node(4);
root1->left->right = new Node(5);
root1->right->right = new Node(6);
// construct the second Binary Tree
//
// 4
// / \
// 1 7
// / / \
// 3 2 6
Node *root2 = new Node(4);
root2->left = new Node(1);
root2->right = new Node(7);
root2->left->left = new Node(3);
root2->right->left = new Node(2);
root2->right->right = new Node(6);
Node *root = mergeTrees(root1, root2);
inorder(root);
return 0;
}
C
// C program to Merge Two Binary Trees
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *left, *right;
};
// Function to print node values in inorder.
void inorder(struct Node *node) {
if (node == NULL)
return;
// Recur on left child
inorder(node->left);
// Print the data of current node
printf("%d ", node->data);
// Recur on right child
inorder(node->right);
}
// Function to merge binary trees
struct Node *mergeTrees(struct Node *t1,
struct Node *t2) {
// if either of the node is null
// return the other node.
if (t1 == NULL)
return t2;
if (t2 == NULL)
return t1;
// 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.
return t1;
}
struct Node *createnode(int data) {
struct Node *newnode = (struct Node *)
malloc(sizeof(struct Node));
newnode->data = data;
newnode->left = newnode->right = NULL;
return newnode;
}
int main() {
// construct the first Binary Tree
// 1
// / \
// 2 3
// / \ \
// 4 5 6
struct Node *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 6
struct Node *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);
struct Node *root = mergeTrees(root1, root2);
inorder(root);
return 0;
}
Java
// Java program to Merge Two Binary Trees
class Node {
int data;
Node left, right;
Node(int value) {
data = value;
left = right = null;
}
}
class GfG {
// Function to print node values in inorder
static void inorder(Node node) {
if (node == null)
return;
// Recur on left child
inorder(node.left);
// Print the data of current node
System.out.print(node.data + " ");
// Recur on right child
inorder(node.right);
}
// Function to merge binary trees
static Node mergeTrees(Node t1, Node t2) {
// if either of the node is null
// return the other node
if (t1 == null)
return t2;
if (t2 == null)
return t1;
// 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
return t1;
}
public static void main(String[] args) {
// construct the first Binary Tree
// 1
// / \
// 2 3
// / \ \
// 4 5 6
Node root1 = new Node(1);
root1.left = new Node(2);
root1.right = new Node(3);
root1.left.left = new Node(4);
root1.left.right = new Node(5);
root1.right.right = new Node(6);
// construct the second Binary Tree
// 4
// / \
// 1 7
// / / \
// 3 2 6
Node root2 = new Node(4);
root2.left = new Node(1);
root2.right = new Node(7);
root2.left.left = new Node(3);
root2.right.left = new Node(2);
root2.right.right = new Node(6);
Node root = mergeTrees(root1, root2);
inorder(root);
}
}
Python
# Python program to Merge Two Binary Trees
class Node:
def __init__(self, data):
self.data = data
self.left = self.right = None
# Function to print node values in inorder
def inorder(node):
if node is None:
return
# Recur on left child
inorder(node.left)
# Print the data of current node
print(node.data, end=" ")
# Recur on right child
inorder(node.right)
# Function to merge binary trees
def mergeTrees(t1, t2):
# if either of the node is null
# return the other node
if t1 is None:
return t2
if t2 is None:
return t1
# 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
return t1
if __name__ == "__main__":
# construct the first Binary Tree
# 1
# / \
# 2 3
# / \ \
# 4 5 6
root1 = 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 6
root2 = 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 Trees
using System;
class Node {
public int data;
public Node left, right;
public Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}
class GfG {
// Function to print node values in inorder
static void inorder(Node node) {
if (node == null)
return;
// Recur on left child
inorder(node.left);
// Print the data of current node
Console.Write(node.data + " ");
// Recur on right child
inorder(node.right);
}
// Function to merge binary trees
static Node mergeTrees(Node t1, Node t2) {
// if either of the node is null
// return the other node
if (t1 == null)
return t2;
if (t2 == null)
return t1;
// 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
return t1;
}
static void Main(string[] args) {
// construct the first Binary Tree
// 1
// / \
// 2 3
// / \ \
// 4 5 6
Node root1 = new Node(1);
root1.left = new Node(2);
root1.right = new Node(3);
root1.left.left = new Node(4);
root1.left.right = new Node(5);
root1.right.right = new Node(6);
// construct the second Binary Tree
//
// 4
// / \
// 1 7
// / / \
// 3 2 6
Node root2 = new Node(4);
root2.left = new Node(1);
root2.right = new Node(7);
root2.left.left = new Node(3);
root2.right.left = new Node(2);
root2.right.right = new Node(6);
Node root = mergeTrees(root1, root2);
inorder(root);
}
}
JavaScript
// Javascript program to Merge Two Binary Trees
class Node {
constructor(value) {
this.data = value;
this.left = null;
this.right = null;
}
}
// Function to print the inorder traversal of the tree.
function inorder(node) {
if (node === null)
return;
// Recur on left child
inorder(node.left);
// Print the value of the current node
console.log(node.data);
// Recur on right child
inorder(node.right);
}
// Function to merge two binary trees
function mergeTrees(t1, t2) {
// If either of the nodes is null, return the other node
if (t1 === null)
return t2;
if (t2 === null)
return t1;
// If both nodes are not null, add the value of t2's
// node to t1's node
t1.data += t2.data;
// Recursively merge left and right children
t1.left = mergeTrees(t1.left, t2.left);
t1.right = mergeTrees(t1.right, t2.right);
// Return the merged tree
return t1;
}
// construct the first Binary Tree
// 1
// / \
// 2 3
// / \ \
// 4 5 6
let root1 = new Node(1);
root1.left = new Node(2);
root1.right = new Node(3);
root1.left.left = new Node(4);
root1.left.right = new Node(5);
root1.right.right = new Node(6);
// construct the second Binary Tree
//
// 4
// / \
// 1 7
// / / \
// 3 2 6
let root2 = new Node(4);
root2.left = new Node(1);
root2.right = new Node(7);
root2.left.left = new Node(3);
root2.right.left = new Node(2);
root2.right.right = new Node(6);
let root = mergeTrees(root1, root2);
inorder(root);
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>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
Node(int x) {
data = x;
left = right = nullptr;
}
};
// Function to perform an inorder traversal
// of the binary tree
void inorder(Node *node) {
// Base case: if the node is null, return
if (node == nullptr)
return;
// Recursively traverse the left subtree
inorder(node->left);
// Print the current node's data
cout<< node->data << " ";
// Recursively traverse the right subtree
inorder(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 tree
if (t1 == nullptr)
return t2;
// If the second tree is null, return the first tree
if (t2 == nullptr)
return t1;
// Stack to store pairs of nodes to be processed
stack<pair<Node *, Node *>> s;
// Initialize the stack with the root
// nodes of both trees
s.push({t1, t2});
while (!s.empty()) {
// Get the top pair of nodes from the stack
pair<Node *, Node *> n = s.top();
s.pop();
// If either node is null, skip this pair
if (n.first == nullptr || n.second == nullptr)
continue;
// Add the data of the second tree's node to
// the first tree's node
n.first->data += n.second->data;
// Process the left children
if (n.first->left == nullptr)
n.first->left = n.second->left;
else {
s.push({n.first->left, n.second->left});
}
// Process the right children
if (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 tree
return t1;
}
int main() {
// Construct the first Binary Tree
// 1
// / \
// 2 3
// / \ \
// 4 5 6
Node *root1 = new Node(1);
root1->left = new Node(2);
root1->right = new Node(3);
root1->left->left = new Node(4);
root1->left->right = new Node(5);
root1->right->right = new Node(6);
// Construct the second Binary Tree
// 4
// / \
// 1 7
// / / \
// 3 2 6
Node *root2 = new Node(4);
root2->left = new Node(1);
root2->right = new Node(7);
root2->left->left = new Node(3);
root2->right->left = new Node(2);
root2->right->right = new Node(6);
Node *root = mergeTrees(root1, root2);
inorder(root);
return 0;
}
Java
// Java program to Merge Two Binary Trees
// using iteration
import java.util.Stack;
class NodePair {
Node tree1, tree2;
NodePair(Node t1, Node t2) {
tree1 = t1;
tree2 = t2;
}
}
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Function to perform inorder traversal of the binary
// tree
static void inorder(Node node) {
if (node == null) {
return;
}
inorder(node.left);
System.out.print(node.data + " ");
inorder(node.right);
}
// Function to merge two binary trees iteratively using
// NodePair
static Node mergeTrees(Node t1, Node t2) {
if (t1 == null) {
return t2;
}
if (t2 == null) {
return t1;
}
// Stack to store pairs of nodes to be processed
Stack<NodePair> stack = new Stack<>();
// Push the root nodes of both trees
// onto the stack
stack.push(new NodePair(t1, t2));
while (!stack.isEmpty()) {
NodePair pair = stack.pop();
Node node1 = pair.tree1;
Node node2 = pair.tree2;
if (node1 == null || node2 == null) {
continue;
}
// Add the data of the second tree's node to the
// first tree's node
node1.data += node2.data;
// If the left child of node1 is null, assign it
// to node2's left child
if (node1.left == null) {
node1.left = node2.left;
}
else {
stack.push(
new NodePair(node1.left, node2.left));
}
// If the right child of node1 is null, assign
// it to node2's right child
if (node1.right == null) {
node1.right = node2.right;
}
else {
stack.push(
new NodePair(node1.right, node2.right));
}
}
// Return the root of the merged tree
return t1;
}
public static void main(String[] args) {
// Construct the first Binary Tree
// 1
// / \
// 2 3
// / \ \
// 4 5 6
Node root1 = new Node(1);
root1.left = new Node(2);
root1.right = new Node(3);
root1.left.left = new Node(4);
root1.left.right = new Node(5);
root1.right.right = new Node(6);
// Construct the second Binary Tree
// 4
// / \
// 1 7
// / / \
// 3 2 6
Node root2 = new Node(4);
root2.left = new Node(1);
root2.right = new Node(7);
root2.left.left = new Node(3);
root2.right.left = new Node(2);
root2.right.right = new Node(6);
Node mergedRoot = mergeTrees(root1, root2);
inorder(mergedRoot);
}
}
Python
# Python program to Merge Two Binary Trees
# using iteration
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# Function to perform inorder traversal of the binary tree
def inorder(node):
# Base case: if the node is null, return
if node is None:
return
# Recursively traverse the left subtree
inorder(node.left)
# Print the current node's data
print(node.data, end=" ")
# Recursively traverse the right subtree
inorder(node.right)
# Function to merge two binary trees iteratively
# using tuple (node1, node2)
def mergeTrees(t1, t2):
# If the first tree is null, return
# the second tree
if t1 is None:
return t2
# If the second tree is null, return the first tree
if t2 is None:
return t1
# Stack to store pairs of nodes to be processed
stack = [(t1, t2)]
while stack:
# Get the top pair of nodes from the stack
node1, node2 = stack.pop()
# If either node is null, skip this pair
if node1 is None or node2 is None:
continue
# Add the data of the second tree's node to
# the first tree's node
node1.data += node2.data
# If the left child of node1 is null, assign it
# to node2's left child
if node1.left is None:
node1.left = node2.left
else:
stack.append((node1.left, node2.left))
# If the right child of node1 is null, assign it
# to node2's right child
if node1.right is None:
node1.right = node2.right
else:
stack.append((node1.right, node2.right))
# Return the root of the merged tree
return t1
if __name__ == "__main__":
# Construct the first Binary Tree
# 1
# / \
# 2 3
# / \ \
# 4 5 6
root1 = 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 6
root2 = 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 iteration
using System;
using System.Collections.Generic;
public class Node {
public int Data;
public Node Left, Right;
public Node(int x) {
Data = x;
Left = Right = null;
}
}
class GfG {
// Function to perform inorder traversal of the binary
// tree
static void Inorder(Node node) {
// Base case: if the node is null, return
if (node == null)
return;
// Recursively traverse the left subtree
Inorder(node.Left);
// Print the current node's data
Console.Write(node.Data + " ");
// Recursively traverse the right subtree
Inorder(node.Right);
}
// Function to merge two binary trees iteratively using
// tuple (node1, node2)
static Node MergeTrees(Node t1, Node t2) {
// If the first tree is null, return the
// second tree
if (t1 == null)
return t2;
// If the second tree is null, return the first tree
if (t2 == null)
return t1;
// Stack to store pairs of nodes to be processed
Stack<Tuple<Node, Node> > stack
= new Stack<Tuple<Node, Node> >();
stack.Push(new Tuple<Node, Node>(t1, t2));
while (stack.Count > 0) {
// Get the top pair of nodes from the stack
var pair = stack.Pop();
Node node1 = pair.Item1;
Node node2 = pair.Item2;
// If either node is null, skip this pair
if (node1 == null || node2 == null)
continue;
// Add the data of the second tree's node to the
// first tree's node
node1.Data += node2.Data;
// If the left child of node1 is null, assign it
// to node2's left child
if (node1.Left == null)
node1.Left = node2.Left;
else
stack.Push(new Tuple<Node, Node>(
node1.Left, node2.Left));
// If the right child of node1 is null, assign
// it to node2's right child
if (node1.Right == null)
node1.Right = node2.Right;
else
stack.Push(new Tuple<Node, Node>(
node1.Right, node2.Right));
}
// Return the root of the merged tree
return t1;
}
static void Main(string[] args) {
// Construct the first Binary Tree
// 1
// / \
// 2 3
// / \ \
// 4 5 6
Node root1 = new Node(1);
root1.Left = new Node(2);
root1.Right = new Node(3);
root1.Left.Left = new Node(4);
root1.Left.Right = new Node(5);
root1.Right.Right = new Node(6);
// Construct the second Binary Tree
// 4
// / \
// 1 7
// / / \
// 3 2 6
Node root2 = new Node(4);
root2.Left = new Node(1);
root2.Right = new Node(7);
root2.Left.Left = new Node(3);
root2.Right.Left = new Node(2);
root2.Right.Right = new Node(6);
Node mergedRoot = MergeTrees(root1, root2);
Inorder(mergedRoot);
}
}
JavaScript
// Javascript program to Merge Two Binary Trees
// using iteration
class Node {
constructor(x) {
this.data = x;
this.left = this.right = null;
}
}
// Function to perform inorder traversal of the binary tree
function inorder(node) {
// Base case: if the node is null, return
if (node === null)
return;
// Recursively traverse the left subtree
inorder(node.left);
// Print the current node's data
console.log(node.data + " ");
// Recursively traverse the right subtree
inorder(node.right);
}
// Function to merge two binary trees iteratively using a
// stack
function mergeTrees(t1, t2) {
// If the first tree is null, return the second tree
if (t1 === null)
return t2;
// If the second tree is null, return the first tree
if (t2 === null)
return t1;
// Stack to store pairs of nodes to be processed
let stack = [];
// Push the root nodes of both trees into the stack
stack.push({tree1 : t1, tree2 : t2});
while (stack.length > 0) {
// Get the top pair of nodes from the stack
let {tree1, tree2} = stack.pop();
// If either node is null, skip this pair
if (tree1 === null || tree2 === null)
continue;
// Add the data of the second tree's node to the
// first tree's node
tree1.data += tree2.data;
// If the left child of tree1 is null, assign it to
// tree2's left child
if (tree1.left === null)
tree1.left = tree2.left;
else
stack.push(
{tree1 : tree1.left, tree2 : tree2.left});
// If the right child of tree1 is null, assign it to
// tree2's right child
if (tree1.right === null)
tree1.right = tree2.right;
else
stack.push(
{tree1 : tree1.right, tree2 : tree2.right});
}
return t1;
}
// Construct the first Binary Tree
// 1
// / \
// 2 3
// / \ \
// 4 5 6
const root1 = new Node(1);
root1.left = new Node(2);
root1.right = new Node(3);
root1.left.left = new Node(4);
root1.left.right = new Node(5);
root1.right.right = new Node(6);
// Construct the second Binary Tree
// 4
// / \
// 1 7
// / / \
// 3 2 6
const root2 = new Node(4);
root2.left = new Node(1);
root2.right = new Node(7);
root2.left.left = new Node(3);
root2.right.left = new Node(2);
root2.right.right = new Node(6);
const mergedRoot = mergeTrees(root1, root2);
inorder(mergedRoot);
Similar Reads
Binary Tree Data Structure A Binary Tree Data Structure is a hierarchical data structure in which each node has at most two children, referred to as the left child and the right child. It is commonly used in computer science for efficient storage and retrieval of data, with various operations such as insertion, deletion, and
3 min read
Introduction to Binary Tree Binary Tree is a non-linear and hierarchical data structure where each node has at most two children referred to as the left child and the right child. The topmost node in a binary tree is called the root, and the bottom-most nodes are called leaves. Introduction to Binary TreeRepresentation of Bina
15+ min read
Properties of Binary Tree This post explores the fundamental properties of a binary tree, covering its structure, characteristics, and key relationships between nodes, edges, height, and levelsBinary tree representationNote: Height of root node is considered as 0. Properties of Binary Trees1. Maximum Nodes at Level 'l'A bina
4 min read
Applications, Advantages and Disadvantages of Binary Tree A binary tree is a tree that has at most two children for any of its nodes. There are several types of binary trees. To learn more about them please refer to the article on "Types of binary tree" Applications:General ApplicationsDOM in HTML: Binary trees help manage the hierarchical structure of web
2 min read
Binary Tree (Array implementation) Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation o
6 min read
Maximum Depth of Binary Tree Given a binary tree, the task is to find the maximum depth of the tree. The maximum depth or height of the tree is the number of edges in the tree from the root to the deepest node.Examples:Input: Output: 2Explanation: The longest path from the root (node 12) goes through node 8 to node 5, which has
11 min read
Insertion in a Binary Tree in level order Given a binary tree and a key, the task is to insert the key into the binary tree at the first position available in level order manner.Examples:Input: key = 12 Output: Explanation: Node with value 12 is inserted into the binary tree at the first position available in level order manner.Approach:The
8 min read
Deletion in a Binary Tree Given a binary tree, the task is to delete a given node from it by making sure that the tree shrinks from the bottom (i.e. the deleted node is replaced by the bottom-most and rightmost node). This is different from BST deletion. Here we do not have any order among elements, so we replace them with t
12 min read
Enumeration of Binary Trees A Binary Tree is labeled if every node is assigned a label and a Binary Tree is unlabelled if nodes are not assigned any label. Below two are considered same unlabelled trees o o / \ / \ o o o o Below two are considered different labelled trees A C / \ / \ B C A B How many different Unlabelled Binar
3 min read
Types of Binary Tree