描述
已知两颗二叉树,将它们合并成一颗二叉树。合并规则是:都存在的结点,就将结点值加起来,否则空的位置就由另一个树的结点来代替。

​合并二叉树​

public class MergeTwoTrees {

static class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
}

/**
*
* @param t1 TreeNode类
* @param t2 TreeNode类
* @return TreeNode类
*/
public TreeNode mergeTrees (TreeNode t1, TreeNode t2) {
// write code here
//总体思想(递归):以t1为根本,将t2拼接到t1中,具体分一下几种情况:
//(1)t1不为空,t2为空
//(2)t1为空,t2不为空
//(3)t1与t2都不为空

if (t1 == null && t2 == null)
return null;

//(1)t1不为空,t2为空
if(t1!=null && t2 == null){
return t1;
}
//(2)t1为空,t2不为空
if(t1==null && t2!=null){
return t2;
}
//(3)t1与t2都不为空
if(t1 != null && t2 != null){
t1.val += t2.val;//合并数据
t1.left = mergeTrees(t1.left,t2.left);//递归左子树
t1.right = mergeTrees(t1.right,t2.right);//递归右子树
}
return t1;
}

public static void main(String[] args) {

}
}