当前位置:网站首页>二叉树——617. 合并二叉树
二叉树——617. 合并二叉树
2022-07-25 23:55:00 【向着百万年薪努力的小赵】
1 题目描述
给你两棵二叉树: root1 和 root2 。
想象一下,当你将其中一棵覆盖到另一棵之上时,两棵树上的一些节点将会重叠(而另一些不会)。你需要将这两棵树合并成一棵新二叉树。合并的规则是:如果两个节点重叠,那么将这两个节点的值相加作为合并后节点的新值;否则,不为 null 的节点将直接作为新二叉树的节点。
返回合并后的二叉树。
注意: 合并过程必须从两个树的根节点开始。
题目来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/merge-two-binary-trees
2 题目示例

示例 2:
输入:root1 = [1], root2 = [1,2]
输出:[2,2]
3 题目提示
两棵树中的节点数目在范围 [0, 2000] 内
-10^4 <= Node.val <= 10^4
4 思路
方法一:深度优先搜索
可以使用深度优先搜索合并两个二叉树。从根节点开始同时遍历两个二叉树,并将对应的节点进行合并。
两个二叉树的对应节点可能存在以下三种情况,对于每种情况使用不同的合并方式。
如果两个二叉树的对应节点都为空,则合并后的二叉树的对应节点也为空;
如果两个二叉树的对应节点只有一个为空,则合并后的二叉树的对应节点为其中的非空节点;
如果两个二叉树的对应节点都不为空,则合并后的二叉树的对应节点的值为两个二叉树的对应节点的值之和,此时需要显性合并两个节点。
对一个节点进行合并之后,还要对该节点的左右子树分别进行合并。这是一个递归的过程。
复杂度分析
时间复杂度:O(min(m, n)),其中m和n分别是两个二叉树的节点个数。对两个二叉树同时进行深度优先搜索,只有当两个二叉树中的对应节点都不为空时才会对该节点进行显性合并操作,因此被访问到的节点数不会超过较小的二叉树的节点数。
空间复杂度:O(min(m, n)),其中m和n分别是两个二叉树的节点个数。空间复杂度取决于递归调用的层数,递归调用的层数不会超过较小的二叉树的最大高度,最坏情况下,二叉树的高度等于节点数。
方法二:广度优先搜索
也可以使用广度优先搜索合并两个二叉树。首先判断两个二叉树是否为空,如果两个二叉树都为空,则合并后的二叉树也为空,如果只有一个二叉树为空,则合并后的二叉树为另一个非空的二叉树。
如果两个二叉树都不为空,则首先计算合并后的根节点的值,然后从合并后的二叉树与两个原始二叉树的根节点开始广度优先搜索,从根节点开始同时遍历每个二叉树,并将对应的节点进行合并。
使用三个队列分别存储合并后的二叉树的节点以及两个原始二叉树的节点。初始时将每个二叉树的根节点分别加入相应的队列。每次从每个队列中取出一个节点,判断两个原始二叉树的节点的左右子节点是否为空。如果两个原始二叉树的当前节点中至少有一个节点的左子节点不为空,则合并后的二叉树的对应节点的左子节点也不为空。对于右子节点同理。
如果合并后的二叉树的左子节点不为空,则需要根据两个原始二叉树的左子节点计算合并后的二叉树的左子节点以及整个左子树。考虑以下两种情况:
- 如果两个原始二叉树的左子节点都不为空,则合并后的二叉树的左子节点的值为两个原始二叉树的左子节点的值之和,在创建合并后的二叉树的左子节点之后,将每个二叉树中的左子节点都加入相应的队列;
- 如果两个原始二叉树的左子节点有一个为空,即有一个原始二叉树的左子树为空,则合并后的二叉树的左子树即为另一个原始二叉树的左子树,此时也不需要对非空左子树继续遍历,因此不需要将左子节点加入队列。
对于右子节点和右子树,处理方法与左子节点和左子树相同。
复杂度分析
时间复杂度:O(min(m, n)),其中m和n分别是两个二叉树的节点个数。对两个二叉树同时进行广度优先搜索,只有当两个二叉树中的对应节点都不为空时才会访问到该节点,因此被访问到的节点数不会超过较小的二叉树的节点数。
空间复杂度:O(min(m, n)),其中m和n分别是两个二叉树的节点个数。空间复杂度取决于队列中的元素个数,队列中的元素个数不会超过较小的二叉树的节点数。
5 我的答案
方法一:深度优先搜索:
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if (t1 == null) {
return t2;
}
if (t2 == null) {
return t1;
}
TreeNode merged = new TreeNode(t1.val + t2.val);
merged.left = mergeTrees(t1.left, t2.left);
merged.right = mergeTrees(t1.right, t2.right);
return merged;
}
}
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if (t1 == null) {
return t2;
}
if (t2 == null) {
return t1;
}
TreeNode merged = new TreeNode(t1.val + t2.val);
Queue<TreeNode> queue = new LinkedList<TreeNode>();
Queue<TreeNode> queue1 = new LinkedList<TreeNode>();
Queue<TreeNode> queue2 = new LinkedList<TreeNode>();
queue.offer(merged);
queue1.offer(t1);
queue2.offer(t2);
while (!queue1.isEmpty() && !queue2.isEmpty()) {
TreeNode node = queue.poll(), node1 = queue1.poll(), node2 = queue2.poll();
TreeNode left1 = node1.left, left2 = node2.left, right1 = node1.right, right2 = node2.right;
if (left1 != null || left2 != null) {
if (left1 != null && left2 != null) {
TreeNode left = new TreeNode(left1.val + left2.val);
node.left = left;
queue.offer(left);
queue1.offer(left1);
queue2.offer(left2);
} else if (left1 != null) {
node.left = left1;
} else if (left2 != null) {
node.left = left2;
}
}
if (right1 != null || right2 != null) {
if (right1 != null && right2 != null) {
TreeNode right = new TreeNode(right1.val + right2.val);
node.right = right;
queue.offer(right);
queue1.offer(right1);
queue2.offer(right2);
} else if (right1 != null) {
node.right = right1;
} else {
node.right = right2;
}
}
}
return merged;
}
}
边栏推荐
- The process of finding free screen recording software - I didn't expect win10 to come with this function
- Optimize the browsing experience of yandere/konachan site with user scripts
- Graph traversal DFS, BFS (code explanation)
- 行为型模式之责任链模式
- What is the difference between'1 and'b1 when assigning values
- 什么是奇偶校验?如何用C语言实现?
- Several ways of writing strings in reverse order
- After entering www.baidu.com in the address bar
- [intelligence question] interview intelligence question
- Array merge method: concat()
猜你喜欢

反射之类加载过程

ArcGIS cuts TIF images (grid data) according to the vector range, merges shp files in batches, cuts vectors in the region according to the vector range, outputs the geographic coordinate system, conve

Leetcode 0919. complete binary tree inserter: array representation of complete binary tree

调用钉钉api报错:机器人发送签名过期;solution:签名生成时间和发送时间请保持在 timestampms 以内

S4/hana ME21N create Po output control message button missing solution (switch EDI output mode brf+ to Nast mode)

Vscode format JSON file

Redis extended data type (jump table /bitmaps/hyperloglog/geospatial)

Dead letter queue and message TTL expiration code

你还在用浏览器自带书签?这款书签插件超赞

LeetCode 0919. 完全二叉树插入器:完全二叉树的数组表示
随机推荐
你还在用浏览器自带书签?这款书签插件超赞
Ratio of learning_ add,ratio_ subtract,ratio_ multiply,ratio_ Use of divide
[debug bug] JS: getFullYear is not a function
Several ways of writing strings in reverse order
From which dimensions can we judge the quality of code? How to have the ability to write high-quality code?
行为型模式之观察者模式
什么叫做 inode ?带你理解 inode 和对于创建文件和删除文件时 inode 都提供了哪些帮助。
ArcGIS cuts TIF images (grid data) according to the vector range, merges shp files in batches, cuts vectors in the region according to the vector range, outputs the geographic coordinate system, conve
Programmer interview Golden Classic 4.12 summation path
Programming password guessing game
1223. Dice simulation range DP
Scroll series
A brief introduction to OWASP
下一代终端安全管理的关键特征与应用趋势
1223. 掷骰子模拟 范围DP
Vscode format JSON file
Storage of data in memory
Good news under the epidemic
热部署和热加载有什么区别?
Leetcode 0136. numbers that appear only once: XOR