C#LeetCode刷题之#617-合并二叉树​​​​​​​​​​​​​​（Merge Two Binary Trees）

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

3
/ \
4   5
/ \   \
5   4   7

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.

Input:

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

Merged tree:

3
/ \
4   5
/ \   \
5   4   7

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

```public class Program {

public static void Main(string[] args) {
var t1 = new TreeNode(1) {
left = new TreeNode(3)
};

var t2 = new TreeNode(2) {
left = new TreeNode(5) {
left = new TreeNode(7),
right = new TreeNode(9)
},
right = new TreeNode(6)
};

var res = MergeTrees(t1, t2);
ShowTree(res);
Console.WriteLine();

res = MergeTrees2(t1, t2);
ShowTree(res);

}

public static void ShowTree(TreeNode node) {
if(node == null) {
Console.Write("null ");
return;
}
Console.Write(\$"{node.val} ");
ShowTree(node.left);
ShowTree(node.right);
}

public static TreeNode MergeTrees(TreeNode t1, TreeNode t2) {
if(t1 == null && t2 == null) return null;
var root = new TreeNode(0);
Merge(t1, t2, ref root);
return root;
}

public static void Merge(TreeNode t1,
TreeNode t2,
ref TreeNode root) {
if(t1 == null && t2 == null) return;
if(t1 == null) {
root = new TreeNode(t2.val);
} else if(t2 == null) {
root = new TreeNode(t1.val);
} else {
root = new TreeNode(t1.val + t2.val);
}
Merge(t1?.left, t2?.left, ref root.left);
Merge(t1?.right, t2?.right, ref root.right);
}

public static TreeNode MergeTrees2(TreeNode t1, TreeNode t2) {
if(t1 != null && t2 != null) {
t1.val = t1.val + t2.val;
t1.left = MergeTrees2(t1.left, t2.left);
t1.right = MergeTrees2(t1.right, t2.right);
return t1;
}
if(t1 == null) return t2;
if(t2 == null) return t1;
return null;
}

public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}

}```

```3 8 7 null null 9 null null 6 null null
3 8 7 null null 9 null null 6 null null```