[LeetCode] 617. Merge Two Binary Trees

本文详细解析了如何将两棵二叉树合并为一棵新树的问题,通过递归算法,实现了节点值的叠加和非空节点的保留,提供了两种实现方式:新建节点和在原节点上修改。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接:https://leetcode.com/problems/merge-two-binary-trees/

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.

给出两个二叉树,想象一下,你要把其中的一个二叉树覆盖在另一个上面,这样相同位置的节点是不是重合了。
对于这些重合的节点,我们将它们的val值相加,得到一个新的节点来代替它们。
在某个位置上,如果没有节点重合,那就使用原来的节点当作新的节点即可。

Example 1:
在这里插入图片描述

2. 解题思路

可以同时遍历这两棵树,每次都遍历同样位置的节点。如果其中一棵树的节点为null,那么该位置的新节点就用另外一棵树同样位置的节点来代替。如果某个位置两棵树都有节点,那么就建一个新的节点,val值取 t1.val + t2.val 的和。

实现代码

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

当然,也可以直接在t1的基础上进行修改,不必每次都新建一个节点

实现代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if(t1 == null){
            return t2;
        }
        if(t2 == null){
            return t1;
        }
        
        t1.val = t1.val+t2.val;
        t1.left = mergeTrees(t1.left , t2.left );
        t1.right = mergeTrees(t1.right , t2.right);
        return t1;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值