문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음
두 개의 이진 트리 root1과 root2가 주어진다.
두 트리를 겹쳐 놓았을 때, 일부 노드는 겹치고 나머지는 겹치지 않는다고 가정하자. 이 두 트리를 새로운 이진 트리로 병합해야 한다. 병합 규칙은 두 노드가 겹치는 경우, 두 노드의 값을 합산하여 병합된 노드의 새로운 값으로 사용하는 것이다. 그렇지 않으면 NOT null인 노드를 새로운 트리의 노드로 사용한다.
병합된 트리를 반환해라.
#1
Input: root1 = [1, 3, 2, 5], root2 = [2, 1, 3, null, 4, null, 7]
Output: [3, 4, 5, 5, 4, null, 7]
#2
Input: root1 = [1], root2 = [1, 2]
Output: [2, 2]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if(root1 == null) return root2;
if(root2 == null) return root1;
root1.val += root2.val;
root1.left = mergeTrees(root1.left, root2.left);
root1.right = mergeTrees(root1.right, root2.right);
return root1;
}
}