The Wayback Machine - https://web.archive.org/web/20240915123443/https://www.geeksforgeeks.org/merge-two-binary-trees-node-sum/
Open In App

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

Last Updated : 13 Jul, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 Pre-order 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++




// 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 */
    cout<<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;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


C




// C program to Merge Two Binary Trees
 
#include<stdio.h>
#include<stdlib.h>
 
/* A binary tree node has data, pointer to left child
   and a pointer to right child */
typedef struct Node
{
    int data;
    struct Node *left, *right;
}Node;
 
/* Helper function that allocates a new node with the
   given data and NULL left and right pointers. */
Node *newNode(int data)
{
    Node *new_node = (Node *)malloc(sizeof(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;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Java




// Java program to Merge Two Binary Trees
 
/* A binary tree node has data, pointer to left child
   and a pointer to right child */
class Node
{
    int data;
    Node left, right;
     
    public Node(int data, Node left, Node right) {
        this.data = data;
        this.left = left;
        this.right = right;
    }
     
     /* Helper method that allocates a new node with the
     given data and NULL left and right pointers. */
     static Node newNode(int data)
     {
         return new Node(data, null, null);
     }
      
     /* Given a binary tree, print its nodes in inorder*/
     static void inorder(Node node)
     {
         if (node == null)
             return;
       
         /* first recur on left child */
         inorder(node.left);
       
         /* then print the data of node */
         System.out.printf("%d ", node.data);
       
         /* now recur on right child */
         inorder(node.right);
     }
      
     /* Method to merge given two binary trees*/
     static Node MergeTrees(Node t1, Node t2)
     {
         if (t1 == null)
             return t2;
         if (t2 == null)
             return t1;
         t1.data += t2.data;
         t1.left = MergeTrees(t1.left, t2.left);
         t1.right = MergeTrees(t1.right, t2.right);
         return t1;
     }
      
     // Driver method
     public static void main(String[] args)
     {
         /* 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);
         System.out.printf("The Merged Binary Tree is:\n");
         inorder(root3);
     }
}
// This code is contributed by Gaurav Miglani


Python3




# Python3 program to Merge Two Binary Trees
 
# Helper class that allocates a new node
# with the given data and None left and
# right pointers.
class newNode:
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
 
# Given a binary tree, prints nodes
# in inorder
def inorder(node):
    if (not node):
        return
 
    # first recur on left child
    inorder(node.left)
 
    # then print the data of node
    print(node.data, end = " ")
 
    # now recur on right child
    inorder(node.right)
 
# Function to merge given two
# binary trees
def MergeTrees(t1, t2):
    if (not t1):
        return t2
    if (not 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
if __name__ == '__main__':
     
    # Let us construct the first Binary Tree
    #     1
    #     / \
    #     2     3
    # / \     \
    # 4 5     6
    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
    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)
 
    root3 = MergeTrees(root1, root2)
    print("The Merged Binary Tree is:")
    inorder(root3)
 
# This code is contributed by PranchalK


C#




// C# program to Merge Two Binary Trees
using System;
 
/* A binary tree node has data, pointer
to left child and a pointer to right child */
public class Node
{
public int data;
public Node left, right;
 
public Node(int data, Node left,
                      Node right)
{
    this.data = data;
    this.left = left;
    this.right = right;
}
 
/* Helper method that allocates a new
node with the given data and NULL left
and right pointers. */
public static Node newNode(int data)
{
    return new Node(data, null, null);
}
 
/* Given a binary tree, print its
   nodes in inorder*/
public static void preorder(Node node)
{
    if (node == null)
    {
        return;
    }
   
    /* then print the data of node */
    Console.Write("{0:D} ", node.data);
 
    /* first recur on left child */
    inorder(node.left);
 
    /* now recur on right child */
    inorder(node.right);
}
 
/* Method to merge given two binary trees*/
public static Node MergeTrees(Node t1, Node t2)
{
    if (t1 == null)
    {
        return t2;
    }
    if (t2 == null)
    {
        return t1;
    }
    t1.data += t2.data;
    t1.left = MergeTrees(t1.left, t2.left);
    t1.right = MergeTrees(t1.right, t2.right);
    return t1;
}
 
// Driver Code
public static void Main(string[] args)
{
    /* 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);
    Console.Write("The Merged Binary Tree is:\n");
    preorder(root3);
}
}
 
// This code is contributed by Shrikant13


Javascript




<script>
 
// Javascript program to Merge Two Binary Trees
class Node
{
    constructor(data)
    {
        this.left = null;
        this.right = null;
        this.data = data;
    }
}
 
// Helper method that allocates a new
// node with the given data and NULL
// left and right pointers.
function newNode(data)
{
    return new Node(data);
}
 
// Given a binary tree, print its
// nodes in inorder
function inorder(node)
{
    if (node == null)
        return;
     
    // First recur on left child
    inorder(node.left);
     
    // Then print the data of node
    document.write(node.data + " ");
     
    // Now recur on right child
    inorder(node.right);
}
   
// Method to merge given two binary trees
function MergeTrees(t1, t2)
{
    if (t1 == null)
        return t2;
    if (t2 == null)
        return t1;
         
    t1.data += t2.data;
    t1.left = MergeTrees(t1.left, t2.left);
    t1.right = MergeTrees(t1.right, t2.right);
    return t1;
}
 
// Driver code
/* Let us construct the first Binary Tree
             1
           /   \
          2     3
         / \     \
        4   5     6
     */
let 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   */
let 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);
 
let root3 = MergeTrees(root1, root2);
document.write("The Merged Binary Tree is:" + "</br>");
inorder(root3);
 
// This code is contributed by divyeshrabadiya07
 
</script>


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

Implementation:

C++




// 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;
}


Java




// Java program to Merge Two Binary Trees
import java.util.*;
 
class GFG{
 
/* A binary tree node has data, pointer to left child
and a pointer to right child */
static class Node
{
    int data;
    Node left, right;
};
 
// Structure to store node pair onto stack
static class snode
{
    Node l, r;
};
 
/* Helper function that allocates a new node with the
given data and null left and right pointers. */
static 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*/
static void inorder(Node  node)
{
    if (node == null)
        return;
 
    /* first recur on left child */
    inorder(node.left);
 
    /* then print the data of node */
    System.out.printf("%d ", node.data);
 
    /* now recur on right child */
    inorder(node.right);
}
 
/* Function to merge given two binary trees*/
 
static Node MergeTrees(Node t1, Node t2)
{
    if ( t1 == null)
        return t2;
    if ( t2 == null)
        return t1;
    Stack<snode> s = new Stack<>();
    snode temp = new snode();
    temp.l = t1;
    temp.r = t2;
    s.add(temp);
    snode n;
    while (! s.isEmpty())
    {
        n = s.peek();
        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 = new snode();
            t.l = n.l.left;
            t.r = n.r.left;
            s.add(t);
        }
        if (n.l.right == null)
            n.l.right = n.r.right;
        else
        {
            snode t = new snode();
            t.l = n.l.right;
            t.r = n.r.right;
            s.add(t);
        }
    }
    return t1;
}
 
// Driver code
public static void main(String[] args)
{
    /* 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);
    System.out.printf("The Merged Binary Tree is:\n");
    inorder(root3);
}
}
 
// This code is contributed by gauravrajput1


Python3




# Python3 program to Merge Two Binary Trees
  
''' A binary tree node has data, pointer to left child
and a pointer to right child '''
class Node:
     
    def __init__(self, data):
         
        self.data = data
        self.left = None
        self.right = None
         
# Structure to store node pair onto stack
class snode:
     
    def __init__(self, l, r):
         
        self.l = l
        self.r = r
  
''' Helper function that allocates a new node with the
given data and None left and right pointers. '''
def newNode(data):
 
    new_node = Node(data)
    return new_node
     
''' Given a binary tree, print its nodes in inorder'''
def inorder(node):
 
    if (not node):
        return;
  
    ''' first recur on left child '''
    inorder(node.left);
  
    ''' then print the data of node '''
    print(node.data, end=' ');
  
    ''' now recur on right child '''
    inorder(node.right);
  
''' Function to merge given two binary trees'''
  
def MergeTrees(t1, t2):
 
    if (not t1):
        return t2;
    if (not t2):
        return t1;
    s = []
     
    temp = snode(t1, t2)
     
    s.append(temp);
    n = None
     
    while (len(s) != 0):
     
        n = s[-1]
        s.pop();
         
        if (n.l == None or n.r == None):
            continue;
             
        n.l.data += n.r.data;
        if (n.l.left == None):
            n.l.left = n.r.left;
        else:
            t=snode(n.l.left, n.r.left)
            s.append(t);
         
        if (n.l.right == None):
            n.l.right = n.r.right;
        else:
 
            t=snode(n.l.right, n.r.right)
            s.append(t);
         
    return t1;
  
# Driver code
if __name__=='__main__':
     
    ''' Let us construct the first Binary Tree
            1
          /   \
         2     3
        / \     \
       4   5     6
    '''
   
    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   '''
     
    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);
   
    root3 = MergeTrees(root1, root2);
    print("The Merged Binary Tree is:");
    inorder(root3);
     
# This code is contributed by rutvik76


C#




// C# program to Merge Two Binary Trees
using System;
using System.Collections.Generic;
 
class GFG{
 
// A binary tree node has data, pointer
// to left child and a pointer to right
// child
public class Node
{
    public int data;
    public Node left, right;
};
 
// Structure to store node pair onto stack
public class snode
{
    public Node l, r;
};
 
// Helper function that allocates a new
// node with the given data and null
// left and right pointers.
static 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
static void inorder(Node  node)
{
    if (node == null)
        return;
 
    // First recur on left child
    inorder(node.left);
 
    // Then print the data of node
    Console.Write(node.data + " ");
 
    // Now recur on right child
    inorder(node.right);
}
 
// Function to merge given two binary trees
static Node MergeTrees(Node t1, Node t2)
{
    if ( t1 == null)
        return t2;
    if ( t2 == null)
        return t1;
         
    Stack<snode> s = new Stack<snode>();
    snode temp = new snode();
    temp.l = t1;
    temp.r = t2;
    s.Push(temp);
    snode n;
     
    while (s.Count != 0)
    {
        n = s.Peek();
        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 = new snode();
            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 = new snode();
            t.l = n.l.right;
            t.r = n.r.right;
            s.Push(t);
        }
    }
    return t1;
}
 
// Driver code
public static void Main(String[] args)
{
    /* 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);
     
    Console.Write("The Merged Binary Tree is:\n");
     
    inorder(root3);
}
}
 
// This code is contributed by aashish1995


Javascript




<script>
  
// JavaScript program to Merge Two Binary Trees
  
/* A binary tree node has data, pointer to left child
and a pointer to right child */
class Node
{
    constructor()
    {
        this.data=0;
        this.left=this.right=null;
    }
}
  
  
// Structure to store node pair onto stack
class snode
{
    constructor()
    {
        this.l=null;
        this.r=null;
    }
}
  
/* Helper function that allocates a new node with the
given data and null left and right pointers. */
function newNode(data)
{
    let 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*/
function inorder(node)
{
    if (node == null)
        return;
   
    /* first recur on left child */
    inorder(node.left);
   
    /* then print the data of node */
    document.write(node.data+" ");
   
    /* now recur on right child */
    inorder(node.right);
}
  
/* Function to merge given two binary trees*/
function MergeTrees(t1,t2)
{
    if ( t1 == null)
        return t2;
    if ( t2 == null)
        return t1;
    let s = [];
    let temp = new snode();
    temp.l = t1;
    temp.r = t2;
    s.push(temp);
    let n;
    while ( s.length!=0)
    {
        n = 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
        {
            let t = new snode();
            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
        {
            let t = new snode();
            t.l = n.l.right;
            t.r = n.r.right;
            s.push(t);
        }
    }
    return t1;
}
  
// Driver code
/* Let us construct the first Binary Tree
            1
          /   \
         2     3
        / \     \
       4   5     6
    */
  
let 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 second Binary Tree
           4
         /   \
        1     7
       /     /  \
      3     2    6   */
let 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);
  
let root3 = MergeTrees(root1, root2);
document.write("The Merged Binary Tree is:<br>");
inorder(root3);
  
  
// This code is contributed by unknown2108
  
</script>


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.

 



Previous Article
Next Article

Similar Reads

Iterative Approach to check if two Binary Trees are Isomorphic or not
Given two Binary Trees we have to detect if the two trees are Isomorphic. Two trees are called isomorphic if one of them can be obtained from another by a series of flips, i.e. by swapping left and right children of a number of nodes. Any number of nodes at any level can have their children swapped. Note: Two empty trees are isomorphic. For example
12 min read
Count half nodes in a Binary tree (Iterative and Recursive)
Given A binary Tree, how do you count all the half nodes (which has only one child) without using recursion? Note leaves should not be touched as they have both children as NULL. Input : Root of below treeOutput : 3 Nodes 7, 5 and 9 are half nodes as one of their child is Null. So count of half nodes in the above tree is 3 Iterative The idea is to
12 min read
Count full nodes in a Binary tree (Iterative and Recursive)
Given A binary Tree, how do you count all the full nodes (Nodes which have both children as not NULL) without using recursion and with recursion? Note leaves should not be touched as they have both children as NULL. Nodes 2 and 6 are full nodes has both child's. So count of full nodes in the above tree is 2 Method: Iterative The idea is to use leve
12 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Table of Content What is Binary Search Algorithm?Conditions to apply Binary Search Algorithm in a Data St
15+ min read
Total number of possible Binary Search Trees and Binary Trees with n keys
Total number of possible Binary Search Trees with n different keys (countBST(n)) = Catalan number Cn = (2n)! / ((n + 1)! * n!) For n = 0, 1, 2, 3, … values of Catalan numbers are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, .... So are numbers of Binary Search Trees. Total number of possible Binary Trees with n different keys (countBT(n)) = countBST(n
12 min read
Check if two Binary Strings can be made equal by doing bitwise XOR of adjacent
Given binary strings S1 and S2 of length N, the task is to check if S2 can be made equal to S1 by performing the following operations on S2: The first operation is Si = Si ? Si+1. ( ? is the XOR operation)The second operation is Si+1 = Si+1 ? Si. Examples: Input: S1 = "00100", S2 = "00011" Output: Yes ?Explanation: We can apply the following operat
6 min read
Merge Two Balanced Binary Search Trees
You are given two balanced binary search trees e.g., AVL or Red-Black Tree. Write a function that merges the two given balanced BSTs into a balanced binary search tree. Let there be m elements in the first tree and n elements in the other tree. Your merge function should take O(m+n) time.In the following solutions, it is assumed that the sizes of t
15+ min read
Iterative function to check if two trees are identical
Two trees are identical when they have same data and arrangement of data is also same. To identify if two trees are identical, we need to traverse both trees simultaneously, and while traversing we need to compare data and children of the trees. Examples: Input : Roots of below trees 10 10 / \ / 5 6 5 Output : falseInput : Roots of below trees 10 1
15+ min read
Iterative method to check if two trees are mirror of each other
Given two binary trees. The problem is to check whether the two binary trees are mirrors of each other or not. Mirror of a Binary Tree: Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged. Trees in the above figure are mirrors of each other. Recommended PracticeTwo Mirror TreesTry It
11 min read
Count consonants in a string (Iterative and recursive methods)
Given a string, count total number of consonants in it. A consonant is an English alphabet character that is not vowel (a, e, i, o and u). Examples of constants are b, c, d, f, and g. Examples : Input : abc de Output : 3 There are three consonants b, c and d. Input : geeksforgeeks portal Output : 12 1. Iterative Method C/C++ Code // Iterative CPP p
7 min read
First uppercase letter in a string (Iterative and Recursive)
Given a string find its first uppercase letterExamples : Input : geeksforgeeKs Output : K Input : geekS Output : S Method 1: linear search Using linear search, find the first character which is capital C/C++ Code // C++ program to find the first // uppercase letter using linear search #include &lt;bits/stdc++.h&gt; using namespace std; // Function
6 min read
Function to copy string (Iterative and Recursive)
Given two strings, copy one string to another using recursion. We basically need to write our own recursive version of strcpy in C/C++ Examples: Input : s1 = "hello" s2 = "geeksforgeeks" Output : s2 = "hello" Input : s1 = "geeksforgeeks" s2 = "" Output : s2 = "geeksforgeeks" Iterative: Copy every character from s1 to s2 starting from index = 0 and
6 min read
Program for average of an array (Iterative and Recursive)
Given an array, the task is to find average of that array. Average is the sum of array elements divided by the number of elements. Examples : Input : arr[] = {1, 2, 3, 4, 5} Output : 3 Sum of the elements is 1+2+3+4+5 = 15 and total number of elements is 5. So average is 15/5 = 3 Input : arr[] = {5, 3, 6, 7, 5, 3} Output : 4.83333 Sum of the elemen
7 min read
Program to count vowels in a string (Iterative and Recursive)
Given a string, count the total number of vowels (a, e, i, o, u) in it. There are two methods to count total number of vowels in a string. Iterative Recursive Examples: Input : abc de Output : 2 Input : geeksforgeeks portal Output : 7Recommended PracticeVowel or NotTry It! 1. Iterative Method: Below is the implementation: C/C++ Code // C++ program
7 min read
Program to check if an array is sorted or not (Iterative and Recursive)
Given an array of size n, write a program to check if it is sorted in ascending order or not. Equal values are allowed in an array and two consecutive equal values are considered sorted. Examples: Input : 20 21 45 89 89 90Output : YesInput : 20 20 45 89 89 90Output : YesInput : 20 20 78 98 99 97Output : NoApproach 1: Recursive approachThe basic ide
9 min read
Find Length of a Linked List (Iterative and Recursive)
Given a Singly Linked List, the task is to find the Length of the Linked List. Examples: Input: LinkedList = 1-&gt;3-&gt;1-&gt;2-&gt;1Output: 5 Input: LinkedList = 2-&gt;4-&gt;1-&gt;9-&gt;5-&gt;3-&gt;6Output: 7 Iterative Approach to Find the Length of a Linked List:The idea is similar to traversal of Linked List with an additional variable to count
11 min read
Search an element in a Linked List (Iterative and Recursive)
Given a linked list and a key, the task is to check if key is present in the linked list or not. Examples: Input: 14 -&gt; 21 -&gt; 11 -&gt; 30 -&gt; 10, key = 14Output: YesExplanation: 14 is present in the linked list. Input: 6 -&gt; 21 -&gt; 17 -&gt; 30 -&gt; 10 -&gt; 8, key = 13Output: NoExplanation: No node in the linked list has value = 13. Ta
13 min read
Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
There are two common ways to traverse a graph, BFS and DFS. Considering a Tree (or Graph) of huge height and width, both BFS and DFS are not very efficient due to following reasons. DFS first traverses nodes going through one adjacent of root, then next adjacent. The problem with this approach is, if there is a node close to root, but not in first
10 min read
Minimize steps to make two integers equal by incrementing them or doing bitwise OR of them
Given two positive integers A and B. The task is to make them equal using minimum operations such that: A = A + 1 (increase a by 1).B = B + 1 (increase b by 1).A = A | B (replace A with the bitwise OR of A and B). Examples: Input: A = 5, B = 9Output: 4Explanation: It is better to use first operation i.e increase A by 1 four times, Input: A = 2, B =
8 min read
Print the sum of array after doing k queries on the array
Given an array, arr[] of size n. Calculate the sum of arr[] by performing k queries on arr[], such that we have to add an element given in array y[], on the basis of the boolean value given in array check[]. For every index i (0&lt;= i &lt;= n - 1): If check[i] = true, Add y[i] to all the odd numbers present in the array.If check[i] = false, Add y[
10 min read
Construct a Maximum Binary Tree from two given Binary Trees
Given two Binary Trees, the task is to create a Maximum Binary Tree from the two given binary trees and print the Inorder Traversal of that tree. What is the maximum Binary Tree? The maximum binary is constructed in the following manner: In the case of both the Binary Trees having two corresponding nodes, the maximum of the two values is considered
8 min read
Iterative Merge Sort for Linked List
Given a singly linked list of integers, the task is to sort it using iterative merge sort. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Merge Sort is often preferred for sorting a linked list. It is discussed here. However, the method discussed above uses Stack for storing recursion calls. This may consume a l
15+ min read
Iterative Merge Sort
Following is a typical recursive implementation of Merge Sort C/C++ Code // Recursive C++ program for merge sort #include&lt;bits/stdc++.h&gt; using namespace std; // Function to merge the two haves // arr[l..m] and arr[m+1..r] of array arr[] void merge(int arr[], int l, int m, int r); // l is for left index and r is // right index of the sub-array
15+ min read
Minimize the max of Array by doing at most K increment and decrement
Given a positive array arr[] of size N (2 ≤ N ≤ 105) and a positive integer K, the task is to minimize the maximum value of arr[] by performing at most K operations where in each operation, you can select any two distinct integers i and j (0 ≤ i, j &lt; N), then increase the value of arr[i] by 1 and decrease the value of arr[j] by 1. Example: Input
9 min read
Compute AND value by doing XOR of given arrays
Given two arrays A[] and B[], the array C[] is formed by the XOR of ai and bi, i.e ci = ai^bi, the task is to find the maximum AND value of all the array elements of C given that A and B can be permuted in any way. Examples: Input: A[] ={1, 0, 0, 3, 3}, B[] = {2, 3, 2, 1, 0}Output: 2Explanation: C [] = {3, 3, 2, 2, 3} on doing AND of array C value
13 min read
Deepest left leaf node in a binary tree | iterative approach
Given a Binary Tree, find the deepest leaf node that is left child of its parent. For example, consider the following tree. The deepest left leaf node is the node with value 9. Examples: Input : 1 / \ 2 3 / / \ 4 5 6 \ \ 7 8 / \ 9 10 Output : 9 Recursive approach to this problem is discussed hereFor iterative approach, idea is similar to Method 2 o
8 min read
Deepest right leaf node in a binary tree | Iterative approach
Given a Binary Tree, find the deepest leaf node that is the right child of its parent. For example, consider the following tree. The deepest right leaf node is the node with the value 10. Examples: Input : 1 / \ 2 3 \ / \ 4 5 6 \ \ 7 8 / \ 9 10 Output : 10 The idea is similar to Method 2 of level order traversal Traverse the tree level by level and
7 min read
Get level of a node in binary tree | iterative approach
Given a Binary Tree and a key, write a function that returns level of the key. For example, consider the following tree. If the input key is 3, then your function should return 1. If the input key is 4, then your function should return 3. And for key which is not present in key, then your function should return 0. Recursive approach to this problem
10 min read
Find the Absolute Difference between the Right View Sum of two Binary Trees
Given two binary trees, the task is to find the sum of the absolute differences between the right view of binary trees. Examples: Input: Tree 1: 10 / \ 5 20 / \ \ 4 7 30 Tree 2: 50 / \ 25 60 / \ / \ 20 30 55 70 Output: 120Explanation: For Tree 1, the right view nodes are 10, 20, and 30. Therefore, the right view sum is 10 + 20 + 30 = 60, and For Tr
11 min read
Check whether a binary tree is a full binary tree or not | Iterative Approach
Given a binary tree containing n nodes. The problem is to check whether the given binary tree is a full binary tree or not. A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has only one child node. Examples: Input : 1 / \ 2 3 / \ 4 5 Outp
8 min read
Article Tags :
Practice Tags :