617. 合并二叉树

617. 合并二叉树_第1张图片

/**
 * 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) {
        TreeNode *t=new TreeNode;
        if(root1==NULL&&root2==NULL){
            return NULL;
        }
        if(root1!=NULL&&root2==NULL){
            return root1;
        }
        if(root2!=NULL&&root1==NULL){
            return root2;
        }
        t->val=root1->val+root2->val;
        t->left=mergeTrees(root1->left,root2->left);
        t->right=mergeTrees(root1->right,root2->right);
        return t;
    }
};

 

你可能感兴趣的:(数据结构(树),算法,leetcode,数据结构)