xinyu04

导航

LeetCode 617 Merge Two Binary Trees DFS+模板

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 merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.

Return the merged tree.

Note: The merging process must start from the root nodes of both trees.

Solution

直接利用原函数进行 \(DFS\) 即可,当左右子树都有节点时,新建节点(其 \(val\) 为子数的 \(val\) 之和),否则则为不为空的子树节点

点击查看代码
/**
 * 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 && root2){
            TreeNode* new_root = new TreeNode(root1->val+root2->val);
            new_root->left = mergeTrees(root1->left, root2->left);
            new_root->right = mergeTrees(root1->right, root2->right);
            return new_root;
        }
        else return root1 ? root1:root2;
    }
};

posted on 2022-07-22 15:15  Blackzxy  阅读(13)  评论(0编辑  收藏  举报