BiruLyu
7/4/2017 - 4:29 PM

## 617. Merge Two Binary Trees(1st).java

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private TreeNode helper(TreeNode t1, TreeNode t2) {
if (t2 == null) return t1;
if (t1 == null) return t2;
t1.val += t2.val;
t1.left = helper(t1.left, t2.left);
t1.right = helper(t1.right, t2.right);
return t1;
}
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
return helper(t1, t2);
}
}

/*
[1,3,2,5]
[2,1,3,null,4,null,7]
[1,2,3]
[1,2,3,4,5,6,7]

[1,2,null,3]
[1,null,2,null,3]
*/``````
``````/**
* 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;

TreeNode left = mergeTrees(t1.left, t2.left);
TreeNode right = mergeTrees(t1.right, t2.right);

t1.val += t2.val;
t1.left = left;
t1.right = right;
return t1;
}
}``````