刷刷刷 Day 20 | 617. 合并二叉树

617. 合并二叉树
LeetCode题目要求

给你两棵二叉树: root1 和 root2 。

想象一下,当你将其中一棵覆盖到另一棵之上时,两棵树上的一些节点将会重叠(而另一些不会)。你需要将这两棵树合并成一棵新二叉树。合并的规则是:如果两个节点重叠,那么将这两个节点的值相加作为合并后节点的新值;否则,不为 null 的节点将直接作为新二叉树的节点。

返回合并后的二叉树。

注意: 合并过程必须从两个树的根节点开始。

图

示例

输入:root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]
输出:[3,4,5,5,4,null,7]
解题思路

合并两个二叉树,从根节点开始,那么就要通过前序遍历(中左右)进行操作。
通过前序遍历递归的方式,终止条件为 两个 二叉树都为空。只要有一个存在节点,就要递归下去。

上代码

class Solution {
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        // 从根节点遍历两个 二叉树
        // 前序遍历,中 左右

        // 确定终止条件
        if (root1 == null && root2 == null) {
            return null;
        }

        int root1Val = 0;
        if (root1 != null) {
            root1Val = root1.val;
        }
        int root2Val = 0;
        if (root2 != null) {
            root2Val = root2.val;
        }

        TreeNode root = new TreeNode(root1Val + root2Val);

        // 左节点 , 右节点
        TreeNode root1Left = null;
        TreeNode root2Left = null;
        TreeNode root1Right = null;
        TreeNode root2Right = null;
        if (root1 != null) {
            root1Left = root1.left;
            root1Right = root1.right;
        }
        if (root2 != null) {
            root2Left = root2.left;
            root2Right = root2.right;
        }
        root.left = mergeTrees(root1Left, root2Left);
        root.right = mergeTrees(root1Right, root2Right);

        return root;
    }
}

附:学习资料链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值