17. Merge Two Binary Trees 融合二叉树
[抄題]:
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提前列出來,實現自動判斷
[一句話思路]:
左邊和左邊融合,右邊和右邊融合
[輸入量]:空:?正常情況:特大:特小:程序里處理到的特殊情況:異常情況(不合法不合理的輸入):
[畫圖]:
[一刷]:
[二刷]:
[三刷]:
[四刷]:
[五刷]:
? [五分鐘肉眼debug的結果]:
[總結]:
[復雜度]:Time complexity: O(n) Space complexity: O(n)
[英文數據結構或算法,為什么不用別的數據結構或算法]:
左右討論還是用的traverse嵌套
[關鍵模板化代碼]:
//left & right :divide into node's left & node's rightnode.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 nullif (t1 == null) {return t2;}if (t2 == null) {return t1;}//left.val + right.val: new val needs new nodeTreeNode node = new TreeNode(t1.val + t2.val);//left & right :divide into node's left & node's rightnode.left = mergeTrees(t1.left, t2.left);node.right = mergeTrees(t1.right, t2.right);return node;} } View Code?
轉載于:https://www.cnblogs.com/immiao0319/p/8566678.html
總結
以上是生活随笔為你收集整理的17. Merge Two Binary Trees 融合二叉树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 绵阳自驾到阿克苏默拉纳额什丁麻扎路过什么
- 下一篇: 网络爬虫入门系列(3) httpClie