617. 合并二叉树(javascript)617. Merge Two Binary Trees

这篇博客探讨了如何合并两个二叉树,通过深度优先搜索(DFS)、先序遍历、中序遍历和后序遍历等方法实现。在合并过程中,当节点重叠时,节点值相加,否则保留非空节点。示例展示了具体的合并步骤,解题思路详述了不同遍历方式下的合并操作。

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

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

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

返回合并后的二叉树。

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

You are given two binary trees root1 and root2.

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 the two trees 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 the new tree.

Return the merged tree.

Note: The merging process must start from the root nodes of both trees.

示例 1:
请添加图片描述

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

示例 2:

输入:root1 = [1], root2 = [1,2]
输出:[2,2]

提示:

  • 两棵树中的节点数目在范围 [0, 2000] 内
  • -104 <= Node.val <= 104

解题思路

可以使用深度优先搜索合并两个二叉树。从根节点开始同时遍历两个二叉树,并将对应的节点进行合并。

  • 两个二叉树的对应节点可能存在以下三种情况,对于每种情况使用不同的合并方式。
  • 如果两个二叉树的对应节点都为空,则合并后的二叉树的对应节点也为空;
  • 如果两个二叉树的对应节点只有一个为空,则合并后的二叉树的对应节点为其中的非空节点;
  • 如果两个二叉树的对应节点都不为空,则合并后的二叉树的对应节点的值为两个二叉树的对应节点的值之和,此时需要显性合并两个节点。

先序遍历

var mergeTrees = function(root1, 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
};

中序遍历

var mergeTrees = function(root1, root2) {
    if(root1==null) return root2
    if(root2==null) return root1
    
    root1.left=mergeTrees(root1.left,root2.left)
    root1.val+=root2.val
    root1.right=mergeTrees(root1.right,root2.right)
    
    return root1
};

后序遍历

var mergeTrees = function(root1, root2) {
    if(root1==null) return root2
    if(root2==null) return root1
    
    root1.left=mergeTrees(root1.left,root2.left)
    root1.right=mergeTrees(root1.right,root2.right)
    root1.val+=root2.val
    
    return root1
};

leetcode:https://leetcode-cn.com/problems/merge-two-binary-trees/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值