算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 合并二叉树,我们先来看题面:
https://leetcode.cn/problems/merge-two-binary-trees/
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.
给你两棵二叉树:root1 和 root2 。
想象一下,当你将其中一棵覆盖到另一棵之上时,两棵树上的一些节点将会重叠(而另一些不会)。你需要将这两棵树合并成一棵新二叉树。合并的规则是:如果两个节点重叠,那么将这两个节点的值相加作为合并后节点的新值;否则,不为 null 的节点将直接作为新二叉树的节点。
返回合并后的二叉树。
注意: 合并过程必须从两个树的根节点开始。
示例
解题
https://blog.youkuaiyun.com/Changersh/article/details/123969046
主要思路:迭代,层序
套层序模板,只不过入队 / 出队的时候变成了两棵树的结点,
最开始的时候还是要判断一下,两个根节点是否是空的
while循环里面,同时出队两棵树的对应结点,
开始的时候直接将root2 的val加到root1上面即可
之后分以下几种情况
root1和root2左节点都不空,就将他们分别入队
root1和root2右节点都不空,分别入队
root1左节点为空,而root2左节点不空,直接把root2左节点赋值给root1
root1右节点为空,而root2右节点不空,直接把root2右节点赋值给root1
(不需要考虑root1不空但是root2 空的结点,因为root1是母树,直接接在自身就好了)
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if (root1 == NULL) return root2;
if (root2 == NULL) return root1;
queue<TreeNode*> que;
// 此时两个根节点一定不空
que.push(root1);
que.push(root2);
while (!que.empty()) {
TreeNode* node1 = que.front();
que.pop();
TreeNode* node2 = que.front();
que.pop();
node1->val += node2->val;
// 如果两个左子树都不空,入队
if (node1->left && node2->left) {
que.push(node1->left);
que.push(node2->left);
}
// 右子树都不空,入队
if (node1->right && node2->right) {
que.push(node1->right);
que.push(node2->right);
}
// 因为是把root1 当作母树,所以root1 结点是空的时候不用再入队了,因为直接把root2 接到它下面了
if (node1->left == NULL && node2->left) {
node1->left = node2->left;
}
if (node1->right == NULL && node2->right) {
node1->right = node2->right;
}
}
return root1;
}
};
上期推文:
LeetCode刷题实战602:好友申请 II :谁有最多的好友