题解 | #合并二叉树#

合并二叉树

https://www.nowcoder.com/practice/7298353c24cc42e3bd5f0e0bd3d1d759

/**
 * struct TreeNode {
 *  int val;
 *  struct TreeNode *left;
 *  struct TreeNode *right;
 *  TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
  public:
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        if (!t1) {
            return t2;
        }
        if (!t2) {
            return t1;
        }

        t1->val += t2->val;  // 这道题没有先后顺序的要求,用先序遍历解题不影响结果
        t1->left = mergeTrees(t1->left, t2->left);
        t1->right = mergeTrees(t1->right, t2->right);

        return t1;
    }
};

全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务