본문 바로가기
Problem Solving/LeetCode

[LeetCode] 617. Merge Two Binary Trees - Java

by graycode 2026. 9. 12.

• 문제 링크

 

Merge Two Binary Trees - LeetCode

Can you solve this real interview question? Merge Two Binary Trees - You are given two binary trees root1 and root2. Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to

leetcode.com

 

• 풀이 코드

public class Solution {

    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if (root1 == null) return root2;
        if (root2 == null) return root1;

        TreeNode node = new TreeNode(root1.val + root2.val);
        node.left = mergeTrees(root1.left, root2.left);
        node.right = mergeTrees(root1.right, root2.right);

        return node;
    }

}

댓글