题解 | #合并二叉树#
合并二叉树
http://www.nowcoder.com/practice/7298353c24cc42e3bd5f0e0bd3d1d759
思路:
通过二叉树的前序遍历方法进行遍历。
同时,t1二叉树作为蓝本进行计算,注意设置两个指针记录t1和t2遍历到的当前位置。
三种情况:
1、t1和t2都拥有的节点进行相加,
2、t1没有t2有的节点,直接接在t1节点上
3、t1有,t2没有的节点不做处理。
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param t1 TreeNode类
* @param t2 TreeNode类
* @return TreeNode类
*/
public TreeNode mergeTrees (TreeNode t1, TreeNode t2) {
// write code here
TreeNode a1 = t1;
TreeNode a2 = t2;
def(a1, a2);
return t1;
}
private static void def(TreeNode a1, TreeNode a2) {
if (a1 == null && a2 == null) {
return;
}
if (a2 != null) {
a1.val = a2.val + a1.val;
if (a1.right == null) {
a1.right = a2.right;
}else {
def(a1.right, a2.right);
}
if (a1.left == null) {
a1.left = a2.left;
}else {
def(a1.left, a2.left);
}
} else {
return;
}
}
}
