一、题目
给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。
你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。
示例 1:
输入: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 输出: 合并后的树: 3 / \ 4 5 / \ \ 5 4 7
注意: 合并必须从两个树的根节点开始。
二、思路
题目的关键词是重叠,就是根结点和根结点重合,左结点和左结点重合,右结点和右结点重合,那么就先遍历两个二叉树的root结点并生成新的root,用递归的方式生成其left、right结点。
三、代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 != null) {
return t2;
} else if (t1 != null && t2 == null) {
return t1;
} else if (t1 == null && t2 == null) {
return null;
}
TreeNode newNode = null;
if (t1 != null && t2 != null) {
newNode = new TreeNode(t1.val + t2.val);
} else if (t1 == null && t2 != null) {
newNode = new TreeNode(t2.val);
} else if (t1 != null && t2 == null) {
newNode = new TreeNode(t1.val);
}
if (newNode !=null){
newNode.left = mergeTrees(t1.left, t2.left);
newNode.right = mergeTrees(t1.right, t2.right);
}
return newNode;
}
}
四、测试效果
人的成长过程真的是一个认知升级的过程 ,其实我之前都不刷leetcode,觉得刷题就是为了应付笔试,我们工作是做业务,哪里有那么多的算法要解决,大学那会儿更是不知道数据结构和算法这门课的重要性,即使老师有说过很重要,但是我当时是不以为然的态度,自己认知水平受限,高人指点也会左耳朵进右耳朵出,我感觉做这些题的最大好处就是强迫自己去思考,而且很直观的感受到不同实现方式时间复杂度和空间复杂度的相对差别,并在工作中加以优化代码。即使是标注为简单的题,要是第一次见,还是要思考好一会儿的,leetcode的测试用例貌似也越来越优秀,能测出自己没考虑到的一些方面。