leetcode---617. Merge Two Binary Trees

Description

Given two binary trees and 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 them 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 new tree.

Example 1:

在这里插入图片描述

Note

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

Coding

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */



//合并算法:
//对应位置如果都存在,把两者相加的和放到t1节点上
//t1存在,t2不存在,什么也不需要操作,直接返回t1指针
//t2存在,t1不存在,什么也不需要操作,直接返回t2指针
//t1左(右)子树存在,t2左(右)子树不存在,把t2子树接到t1的左(右)子树上,结束本次操作
//t2左(右)子树存在,t1左(右)子树不存在,把t1子树接到t2的左(右)子树上,结束本次操作


class Solution {
public:
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        if (t1 && t2) {
        t1->val = t1->val + t2->val;

        if (t1->left) {
            mergeTrees(t1->left, t2->left);
        }else {
            t1->left = t2->left;
        }

        if (t1->right) {
            mergeTrees(t1->right, t2->right);
        } else {
            t1->right = t2->right;
        }

    } else {
        if (t2) {
            return t2;
        } else {
            return t1;
        }
    }
        return t1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值