代码随想录 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
    }
}
相关推荐
不会就选b5 小时前
算法日常・每日刷题--<贪心>25
数据结构·算法
Cccp.1238 小时前
【leetcode】(七)前缀树和贪心算法
数据结构·leetcode·贪心算法
千里码aicood8 小时前
基于CART算法的图书分类系统设计与实现
数据库·算法·分类
做cv的小昊9 小时前
【World Model】π0.5:a Vision-Language-Action Model with Open-World Generalization
人工智能·算法·机器学习·大模型·多模态·vla·世界模型
لا معنى له9 小时前
World-In-World: World Models in a Closed-Loop World
算法
Logic10111 小时前
C语言/数据结构位运算题解:异或XOR找出多任务下载器中的“独特下载速度“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
Discipline102911 小时前
尼泊尔河流流量:天气驱动的预测与高流量风险
人工智能·算法
XuCoder12 小时前
改一个数,右边全得重算,这题怎么扛住两万次查询
算法
小羊没烦恼!12 小时前
在Scrum中实施敏捷建模
java·开发语言·windows·算法·c#