给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。
你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。
解题思路
两颗二叉树的当前节点一共有四种情况:
- t1节点不为空,t2不为空
- t1节点不为空,t2为空
- t1节点为空,t2不为空
- t1节点为空,t2为空
class Solution {
//递归合并
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if (t1 != null && t2 != null) {
//t1节点不为空,t2不为空
t1.val += t2.val;
t1.left = mergeTrees(t1.left, t2.left);
t1.right = mergeTrees(t1.right, t2.right);
return t1;
}
//t1节点不为空,t2为空
else if (t1 != null && t2 == null) return t1;
//t1节点为空,t2不为空
else if (t1 == null && t2 != null) return t2;
//t1节点为空,t2为空
else return null;
}
}