Algorithm 문제풀이/Leetcode

(Easy - DFS) Leetcode - 617. Merge Two Binary Trees

j-engine 2024. 6. 24. 15:43

이진 트리 두 개가 주어졌을 때 트리들을 하나의 트리로 합치는 문제입니다.

병합 규칙 :

       1) 두 트리의 노드가 모두 존재하면 두 노드의 값을 합쳐 병합된 트리의 노드의 값으로 사용

       2) 두 노드 중 null이 아닌 노드를 병합된 트리의 노드로 사용

       3) 둘 다 null이면 nullptr

 

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
 
    TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
        if (root1 && root2) { // 두 노드가 모두 존재하면
            root1->val += root2->val; // 값 합치기
            root1->left = mergeTrees(root1->left, root2->left); // 왼쪽 자식
            root1->right = mergeTrees(root1->right, root2->right); // 오른쪽 자식
        }
        else if (root2) // root2 노드가 null이 아니라면
            root1 = root2; // root2 노드를 병합된 노드로 사용
        
        // 만약 root1 노드가 null이 아니라면 root1이 병합된 노드로 사용되고
        // 두 노드 모두 null이라면 nullptr이 반환
        return root1;   
    }