[LeetCode] Merge Two Binary Trees

아르당·2026년 2월 7일

LeetCode

목록 보기
136/213
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

두 개의 이진 트리 root1과 root2가 주어진다.

두 트리를 겹쳐 놓았을 때, 일부 노드는 겹치고 나머지는 겹치지 않는다고 가정하자. 이 두 트리를 새로운 이진 트리로 병합해야 한다. 병합 규칙은 두 노드가 겹치는 경우, 두 노드의 값을 합산하여 병합된 노드의 새로운 값으로 사용하는 것이다. 그렇지 않으면 NOT null인 노드를 새로운 트리의 노드로 사용한다.

병합된 트리를 반환해라.

Example

#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]

Constraints

  • 두 개의 트리의 노드 수는 [0, 2000] 범위에 있다.
  • -10^4 <= Node.val <= 10^4

Solved

/**
 * 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;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글