使用额外空间的版本 比较清晰。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
return merge(t1,t2);
}
private TreeNode merge (TreeNode t1, TreeNode t2)
{
if(t1==null&&t2==null) return null;
TreeNode newNode = new TreeNode(0);
if(t1==null)
newNode.val=t2.val;
else if(t2==null)
newNode.val=t1.val;
else
newNode.val=t1.val+t2.val;
newNode.left=merge(t1==null?t1:t1.left,t2==null?t2:t2.left);
newNode.right=merge(t1==null?t1:t1.right,t2==null?t2:t2.right);
return newNode;
}
}
不使用额外空间的版本,直接拼接。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
return merge(t1,t2);
}
private TreeNode merge (TreeNode t1, TreeNode t2)
{
if(t1==null&&t2==null) return null;
if(t1==null)
return t2;
else if(t2==null)
return t1;
else
t1.val=t1.val+t2.val;
t1.left=merge(t1.left,t2.left);
t1.right=merge(t1.right,t2.right);
return t1;
}
}