[抄题]:
Given two binary trees and 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 them 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 new tree.
Example 1:
Input: Tree 1 Tree 2 1 2 / / 3 2 1 3 / 5 4 7 Output: Merged tree: 3 / 4 5 / 5 4 7
[暴力解法]:
时间分析:
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
[思维问题]:
以为要从上往下讨论是否有空节点:实际上是讨论不出来的,特殊情况要当作corner case提前列出来,实现自动判断
[一句话思路]:
左边和左边融合,右边和右边融合
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
- 出现新的数值就要新建一个节点:以前真不知道
- 左、右子树情况不同时,分为node.left 和node.right两边去讨论就行了,第二次见了应该学会了
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
DC和traverse的区别就是有等号和没等号
[复杂度]:Time complexity: O(n) Space complexity: O(n)
[英文数据结构或算法,为什么不用别的数据结构或算法]:
左右讨论还是用的traverse嵌套
[关键模板化代码]:
//left & right :divide into node's left & node's right node.left = mergeTrees(t1.left, t2.left); node.right = mergeTrees(t1.right, t2.right);
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
[代码风格] :
/** * 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) { //corner case:left is null or right is null if (t1 == null) { return t2; } if (t2 == null) { return t1; } //left.val + right.val: new val needs new node TreeNode node = new TreeNode(t1.val + t2.val); //left & right :divide into node's left & node's right node.left = mergeTrees(t1.left, t2.left); node.right = mergeTrees(t1.right, t2.right); return node; } }
20/05/10
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public TreeNode mergeTrees(TreeNode t1, TreeNode t2) { if (t1 == null) return t2; if (t2 == null) return t1; TreeNode mergedNode = new TreeNode(); mergedNode.val = t1.val + t2.val; mergedNode.left = mergeTrees(t1.left, t2.left); mergedNode.right = mergeTrees(t1.right, t2.right); return mergedNode; } }