Merge Two Binary Tree
Merge Two Binary 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)

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:


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.

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 upto n in case of a skewed tree.