13.Merge Two Binary Trees

Example 1:

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

Output: 
Merged tree:
	     3
	    / \
	   4   5
	  / \   \ 
	 5   4   7

Solution: (Using Stack)

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

class Solution
{
public:
    TreeNode *mergeTrees(TreeNode *t1, TreeNode *t2)
    {

        if (t1 == NULL && t2 == NULL)
        {
            return t1;
        }
        else if (!t1)
        {
            return t2;
        }
        else if (!t2)
        {
            return t1;
        }

        stack<pair<TreeNode *, TreeNode *>> s;
        s.push({t1, t2});

        while (!s.empty())
        {

            TreeNode *p1 = s.top().first;
            TreeNode *p2 = s.top().second;
            s.pop();

            p1->val = p1->val + p2->val;

            if (p1->left && p2->left)
            {
                s.push({p1->left, p2->left});
            }
            else
            {
                if (p2->left && !p1->left)
                {
                    p1->left = p2->left;
                }
            }

            if (p1->right && p2->right)
            {
                s.push({p1->right, p2->right});
            }
            else
            {
                if (p2->right && !p1->right)
                {
                    p1->right = p2->right;
                }
            }
        }

        return t1;
    }
};

Last updated