Friday, September 17, 2021

    Merge Two Binary Trees

    Must Read

    We started this site to inspire young minds to motivate and encourage them towards Programming Language. In this site you will get programming tutorials, tech, programming facts, programming fun and programming blogs.

    In this article, we learn how to Merge Two Binary Trees with example and two different approaches. First approach is In Java using recursion (By creating the new tree) and Second approach is In Java using stack (By storing the result in first tree).

    Question :

    Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

    You 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 NOT null node will be used as the node of new tree.

    Example 1:

    Tree 1                     Tree 2
    1                          2
    / \                       / \
    3   2                     1   3
    /                           \   \
    5                             4   7
    Merged tree:
    / \
    4   5
    / \   \
    5   4   7

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

    Approach 1: In Java using recursion (By creating the new tree)
    Public class TreeTraversal{
         Public TreeNode MergeTree (TreeNode t1, TreeNode t2){
              if(t1==null && t2==null)return null;
              int val = (t1==null?0:t1.val)+(t2==null?0:t2.val);
              TreeNode newNode = new TreeNode(val);
              newNode.Left=MergeTree(t1==null?null:t1.Left, t2==null?null:t2.Left ) ;
              newNode.Right=MergeTree(t1==null?null:t1. Right , t2==null?null:t2. Right ) ;
             return newNode;

    Complexity Analysis

    • Time complexity : O(m). A total of m nodes need to be traversed. Here, m represents the minimum number of nodes from the two given trees.
    • Space complexity : O(m). The depth of the recursion tree can go upto m in the case of a skewed tree. In average case, depth will be O(logm).
    Optimized Code:
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode(int x) { val = x; }
     * }
    public class Solution {
      public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
      if(t1 == null) return t2;
      if(t2 == null) return t1;
      t1.val = t1.val + t2.val;
      t1.left = mergeTrees(t1.left, t2.left);
      t1.right = mergeTrees(t1.right, t2.right);
      return t1;


    Approach 2: In Java using stack (By storing the result in first tree)
    In this approach we will take the use of stack. We will store the element on the stack as [Node of Tree1, Node of Tree2].
    We will store the result in the tree 1. If the Both Tree having the node then push them onto the stack. If left child of the tree is null then store the left of the second tree onto the first tree. Do same for the right sub-tree. Do this process untill the stack is empty. After each and every iteration we will pop the elements.
    Public class TreeTraversal {
         Public TreeNode MergeTree(TreeNode t1, TreeNode t2){
         if(t1==null) return t2;
         Stack <TreeNode[]>  stack = new stack <>();
         stack.push(new TreeNode[] {t1, t2});
             TreeNode [] t= stack.pop();
              if(t[0]==null || t[1]==null){
                stack.push(new TreeNode[] {t[0].left, t[1].left});
                stack.push(new TreeNode[] {t[0].right, t[1]. right });
           return t1;  

    Test case : 

    Answer: [2,2,4]

    Complexity Analysis

    • Time complexity : O(n). We traverse over a total of n nodes. Here, n refers to the smaller of the number of nodes in the two trees.
    • Space complexity : O(n). The depth of stack can grow up-to n in case of a skewed tree.

    See More: Invert Binary Tree

    Latest Articles

    More Recipes Like This