Reference: LeetCode
Difficulty: Easy

Problem

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.

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

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Input: 
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7

Analysis

Methods:

  1. Recursion

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
    if (t1 == null || t2 == null) { // including both null
    return (t1 == null) ? t2 : t1;
    }
    // by now t1 and t2 are not null
    t1.val += t2.val;
    t1.left = mergeTrees(t1.left, t2.left);
    t1.right = mergeTrees(t1.right, t2.right);
    return t1;
    }

    Time: $O(N)$
    Space: $O(h)$

  2. Iteration

    • Use a stack to store TreeNode[].
    • p1 and p2 are the current roots, they could not be null. However, children could be null.
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
      if (t1 == null || t2 == null) {
      return (t1 == null) ? t2 : t1;
      }
      Stack<TreeNode[]> stack = new Stack<>();
      stack.push(new TreeNode[] { t1, t2 });
      while (stack.size() > 0) {
      TreeNode[] ps = stack.pop();
      TreeNode p1 = ps[0], p2 = ps[1];
      if (p1 == null || p2 == null) {
      continue;
      }
      p1.val += p2.val;
      // left
      if (p1.left == null) {
      p1.left = p2.left;
      } else { // if p1.left is not null, we need to add p2.left.val to p1.left.val
      stack.push(new TreeNode[] {p1.left, p2.left});
      }
      // right
      if (p1.right == null) {
      p1.right = p2.right;
      } else {
      stack.push(new TreeNode[] {p1.right, p2.right});
      }
      }
      return t1;
      }
      Time: $O(N)$
      Space: $O(h)$