본문 바로가기

Algorithm/자료구조

(C++) - LeetCode (easy) 617. Merge Two Binary Trees

반응형

https://leetcode.com/problems/merge-two-binary-trees/description/

 

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

재귀로 tree를 만드는 문제였습니다.

📕 풀이방법

📔 풀이과정

1. 기저 case는 roo1이 null이면 root2를, root2가 null이면 root1을 반환해줍니다. 2. 현재 node를 새롭게 선언해 현재 root의 val을 더해 넣어준 뒤 왼쪽 tree와 오른쪽 tree에서 재귀함수의 결과를 이어줍니다.3. 만들어진 새로운 node mergedTree를 반환해줍니다.


📕 Code

📔 C++

/**
 * 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) {}
 * };
 */
class Solution {
public:
    TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
        if(root1 == NULL ) {
            return root2;
        }
        if(root2 == NULL) {
            return root1;
        }
        TreeNode* mergedTree = new TreeNode();
        mergedTree->val = root1->val + root2->val;
        mergedTree->left = mergeTrees(root1->left, root2->left);
        mergedTree->right = mergeTrees(root1->right, root2->right);
        return mergedTree;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.