617. 合并二叉树
递归解法
思路是将 root2 合并到 root1,最后返回 root1
执行用时:0 ms, 在所有 Java 提交中击败了100.00% 的用户 内存消耗:38.2 MB, 在所有 Java 提交中击败了97.02% 的用户
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
// 如果root1与root2其中一个为空,则返回不为空的
if (root1 == null || root2 == null)
return root1 == null ? root2 : root1;
// 将root2累加到root1
root1.val += root2.val;
// 递归合并
root1.left = mergeTrees(root1.left, root2.left);
root1.right = mergeTrees(root1.right, root2.right);
// 直接返回root1
return root1;
}
}