Merge Two Binary Trees

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求

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.

给出两个二叉树并想象当你把其中一个覆盖另一个时,两棵树的一些节点重叠,而其他树则不重叠。

您需要将它们合并到一个新的二叉树中。 合并规则是,如果两个节点重叠,则将节点值加起来作为合并节点的新值。 否则,NOT null节点将用作新树的节点。
在这里插入图片描述

2,题目思路

这道题,即对树的操作。一般来说,对于树的操作,都利用了递归的方法来去实现。

对于这道题,我们可以看出,是要求合并两颗二叉树。经过分析可以得知:

  • 普通节点合并普通节点,得到新节点、值为二者的和;
  • 普通节点合并空节点,得到的还是普通节点;
  • 空节点合并空节点,得到的是空节点;

对于第二点和第三点,其实合并为一点。

于是,就可以得到算法的设计方法。

3,代码实现

static auto speedup = [](){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return nullptr;
}();


class Solution {
public:
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        if(t1 == nullptr)  
            return t2;      
        if(t2 == nullptr)
            return t1;
        
        TreeNode *root = new TreeNode(t1->val + t2->val);
        root->left = mergeTrees(t1->left, t2->left);
        root->right = mergeTrees(t1->right,t2->right);
        
        return root;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值