用递归的方法去遍历二叉树是最简单的方法
public class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if (t1 == null)
return t2;
if (t2 == null)
return t1;
t1.val += t2.val; //中,可以对这行代码进行位置调整,实现中序和后序遍历
t1.left = mergeTrees(t1.left, t2.left); //左
t1.right = mergeTrees(t1.right, t2.right); //右
return t1;
}
}
另一种方法,参考原作者