代码随想录 617.合并二叉树

题目要求:

1.如果两个节点重叠,则两个节点值相加作为合并后节点的新值。

2.否则,不为null的节点将直接作为新二叉树的节点。

3.合并过程必须从两个树的根节点开始。

思路:同时遍历两个二叉树,其实和遍历一个树的逻辑是一样的,只不过需要传入两个树的节点同时操作。

方法一:前序遍历递归(使用中序、后序遍历也可)。

1.确定递归函数的参数和返回值:因为要合并两棵树,所以参数是两个二叉树的根节点,返回值是合并后二叉树的根节点。

java 复制代码
TreeNode mergeTrees(TreeNode root1, TreeNode root2)

2.确定终止条件:因为传入了两个树,那么就有两个树遍历的节点root1和root2。

(1)如果root1 == null,两个树合并之后就是root2;

(2)反过来如果root2 == null,两个树合并之后就是root1。

(3)如果两个树都是null,合并之后自然是null(可省略不写)。

java 复制代码
        if(root1 == null){
            return root2;
        }
        if(root2 == null){
            return root1;
        }

3.确定单层递归的逻辑:借助root1树存放合并后树的节点值。接下来root1的左子树就是合并root1和root2后的左子树;root1的右子树就是合并root1和root2后的右子树。最终root1就是合并后的根节点。

java 复制代码
        root1.val += root2.val;
        root1.left = mergeTrees(root1.left,root2.left);
        root1.right = mergeTrees(root1.right,root2.right);
        return root1;

附代码:

java 复制代码
    class Solution {
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if(root1 == null){
            return root2;
        }
        if(root2 == null){
            return root1;
        }
        root1.val += root2.val;
        root1.left = mergeTrees(root1.left,root2.left);
        root1.right = mergeTrees(root1.right,root2.right);
        return root1;
    }
}

方法二:层序遍历迭代法

思路:把两个树的节点同时加入队列。

附代码:

java 复制代码
    class Solution {
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        LinkedList<TreeNode> queue = new LinkedList<>();
        if(root1 == null) return root2;
        if(root2 == null) return root1;
        queue.add(root1);
        queue.add(root2);
        while(queue.size() > 0){
            TreeNode t1 = queue.remove();
            TreeNode t2 = queue.remove();
            //此时两个节点一定不为空,val值相加
            t1.val += t2.val;
            if(t1.left != null && t2.left != null){
                queue.add(t1.left);
                queue.add(t2.left);
            }
            if(t1.right != null && t2.right != null){
                queue.add(t1.right);
                queue.add(t2.right);
            }
            //如果t1的左节点为空,则把t2的左节点赋值过去
            if(t1.left == null && t2.left != null){
                t1.left = t2.left;
            }
            //如果t1的右节点为空,则把t2的右节点赋值过去
            if(t1.right == null && t2.right != null){
                t1.right = t2.right;
            }
        }
        return root1; //返回合并后的root1
    }
}
相关推荐
vibecoding日记6 小时前
双非如何快速入职字节等大厂大模型?真实案例分析:推理优化和投机解码
算法·求职·大模型工程师
yszaygr21388 小时前
Verilog参数化游程编码RLE模块
算法
望易8 小时前
刚设计的大模型架构-双域耦合认知框架
算法·架构
复杂网络12 小时前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
HjhIron1 天前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩1 天前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹1 天前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术1 天前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
浮生望1 天前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法