C++ Merge Two Binary Trees














































C++ Merge Two Binary Trees



Merge Two Binary Trees by doing Node Sum (Recursive and Iterative)


Given two binary trees. We 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 non-null node will be used as the node of new tree.

Example:

Input: 
Tree 1 Tree 2
2 3
/ /
1 4 6 1
/
5 2 7

Output: Merged tree:
5
/
7 5
/
5 2 7

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

Recursive Algorithm:

  1. Traverse the tree in Preorder fashion
  2. Check if both the tree nodes are NULL
    1. If not, then update the value
  3. Recur for left subtrees
  4. Recur for right subtrees
  5. Return root of updated Tree
// C++ program to Merge Two Binary Trees
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node
{
int data;
struct Node *left, *right;
};
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
Node *newNode(int data)
{
Node *new_node = new Node;
new_node->data = data;
new_node->left = new_node->right = NULL;
return new_node;
}
/* Given a binary tree, print its nodes in inorder*/
void inorder(Node * node)
{
if (!node)
return;
/* first recur on left child */
inorder(node->left);
/* then print the data of node */
printf("%d ", node->data);
/* now recur on right child */
inorder(node->right);
}
/* Function to merge given two binary trees*/
Node *MergeTrees(Node * t1, Node * t2)
{
if (!t1)
return t2;
if (!t2)
return t1;
t1->data += t2->data;
t1->left = MergeTrees(t1->left, t2->left);
t1->right = MergeTrees(t1->right, t2->right);
return t1;
}
// Driver code
int main()
{
/* Let us 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);
/* Let us construct the second Binary Tree
4
/
1 7
/ /
3 2 6 */
Node *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 *root3 = MergeTrees(root1, root2);
printf("The Merged Binary Tree is:\n");
inorder(root3);
return 0;
}
Output:

The Merged Binary Tree is:
7 3 5 5 2 10 12

Complexity Analysis:

  • Time complexity : O(n)
    A total of n nodes need to be traversed. Here, n represents the minimum number of nodes from the two given trees.
  • Auxiliary Space : O(n)
    The depth of the recursion tree can go upto n in case of a skewed tree. In average case, depth will be O(logn).

Iterative Algorithm:

  1. Create a stack
  2. Push the root nodes of both the trees onto the stack.
  3. While the stack is not empty, perform following steps :
    1. Pop a node pair from the top of the stack
    2. For every node pair removed, add the values corresponding to the two nodes and update the value of the corresponding node in the first tree
    3. If the left child of the first tree exists, push the left child(pair) of both the trees onto the stack.
    4. If the left child of the first tree doesn't exist, append the left child of the second tree to the current node of the first tree
    5. Do same for right child pair as well.
    6. If both the current nodes are NULL, continue with popping the next nodes from the stack.
  4. Return root of updated Tree
// C++ program to Merge Two Binary Trees
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node
{
int data;
struct Node *left, *right;
};
// Structure to store node pair onto stack
struct snode
{
Node *l, *r;
};
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
Node *newNode(int data)
{
Node *new_node = new Node;
new_node->data = data;
new_node->left = new_node->right = NULL;
return new_node;
}
/* Given a binary tree, print its nodes in inorder*/
void inorder(Node * node)
{
if (! node)
return;
/* first recur on left child */
inorder(node->left);
/* then print the data of node */
printf("%d ", node->data);
/* now recur on right child */
inorder(node->right);
}
/* Function to merge given two binary trees*/
Node* MergeTrees(Node* t1, Node* t2)
{
if (! t1)
return t2;
if (! t2)
return t1;
stack<snode> s;
snode temp;
temp.l = t1;
temp.r = t2;
s.push(temp);
snode n;
while (! s.empty())
{
n = s.top();
s.pop();
if (n.l == NULL|| n.r == NULL)
continue;
n.l->data += n.r->data;
if (n.l->left == NULL)
n.l->left = n.r->left;
else
{
snode t;
t.l = n.l->left;
t.r = n.r->left;
s.push(t);
}
if (n.l->right == NULL)
n.l->right = n.r->right;
else
{
snode t;
t.l = n.l->right;
t.r = n.r->right;
s.push(t);
}
}
return t1;
}
// Driver code
int main()
{
/* Let us 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);
/* Let us construct the second Binary Tree
4
/
1 7
/ /
3 2 6 */
Node *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 *root3 = MergeTrees(root1, root2);
printf("The Merged Binary Tree is:\n");
inorder(root3);
return 0;
}

Output:

The Merged Binary Tree is:
7 3 5 5 2 10 12

Complexity Analysis:

  • Time complexity : O(n)
    A total of n nodes need to be traversed. Here, n represents the minimum number of nodes from the two given trees.
  • Auxiliary Space : O(n)
    The depth of the stack can go upto n in case of a skewed tree.

More Articles of M Mounika:

Name Views Likes
C++ Segmented Sieve (Print Primes In a Range) 162 0
C++ Sieve Of Erastosthenes 135 0
C++ Gold Mine Problem 295 0
C++ Merge K Sorted Arrays 117 0
C++ K Centers Problem 240 0
C++ Find Nth Catalan Number 311 0
C++ Inplace Rotate square matrix by 90 degrees 285 0
C++ Find Non Repeating Elements in Array 87 0
C++ Merge Two Binary Trees 121 0
C++ Sum of Numbers From Root To Leaf Paths 89 0
C++ Meta Strings 91 0
C++ Flood Fill Algorithm 402 0
C++ smallest substring with maximum distinct characters 199 0
C++ Smallest window with all characters in string 93 0
C++ Minimum Removal of Characters from string to make its permutation as palindrome 87 0
C++ Minimum characters added at front of string in palindrome conversion 69 0
C++ Number of Bracket Reversals needed to make expression Balanced 72 0
C++ String to Palindrome with Append Function 83 0
C++ WildCard pattern matching 76 0
C++ Anagram substring Search 72 0
C++ Manachars Algorithm 74 0
C++ Search String in Grid 83 0
C++ String Matching(Z Algorithm) 67 0
C++ String Matching(Naive Algorithm) 113 0
C++ String Matching(KMP Algorithm) 140 0
C++ Remove Duplicates From String 110 0
C++ Basics of String Manipulation 85 1
C++ Disjoint Data Structure Cycle Detection 87 0
C++ Problem On Disjoint Data Structures 95 0
C++ Disjoint Data Structures Part3 79 0
Disjoint Data Structures Part2 90 0
Disjoint Data Structures 93 1
C++ Segment Trees 321 2
C++ Trie Cost of Data 290 1
C++ Trie Datastructure 279 1
C++ Greedy Approach Minimum number of coins 526 0
C++ Greedy Approach Maximum height Pyramid 328 1
C++ Greedy Approach String lexicographically largest subsequence 247 0
C++ Greedy Approach Lexicographically largest subsequence 364 0
C++ Greedy Approach Prims MST 398 1
C++ Greedy Approach Krushkals MST 458 1
C++ Greedy Approach N-array maximum sum 333 1
C++ Greedy Approach Policemen Catch Thieves 563 1
C++ Greedy Approach Maximum product Subset 546 1
C++ Greedy Approach Minimum Product Subset 349 1
C++ Greedy Approach Fractional Knapsack 737 1
C++ Greedy Approach-Activity Selection Problem 745 1
C++ Greedy Approach-Egyptian Fractions 640 0
C++ Greedy Approach-Huffman Codes 1031 1
C++ Introduction to Greedy Approach 955 2

Comments