欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

617. 合并二叉树(c++)

程序员文章站 2022-03-03 10:36:17
...

暴力解,当t1为空返回t2,当t2为空返回t1。当t1,t2都有值,new新节点为两个节点的和,新节点左子树为原始节点左子树合并,新节点右子树为原始节点右子树合并。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        if (t1 == NULL)
        {
            return t2;
        }
        if (t2 == NULL)
        {
            return t1;
        }
        TreeNode* newnode = new TreeNode(t1->val + t2->val);
        newnode->left = mergeTrees(t1->left, t2->left);
        newnode->right = mergeTrees(t1->right, t2->right);
        return newnode;

    }
};