日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

17. Merge Two Binary Trees 融合二叉树

發布時間:2024/10/12 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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提前列出來,實現自動判斷

[一句話思路]:

左邊和左邊融合,右邊和右邊融合

[輸入量]:空:?正常情況:特大:特小:程序里處理到的特殊情況:異常情況(不合法不合理的輸入):

[畫圖]:

[一刷]:

  • 出現新的數值就要新建一個節點:以前真不知道
  • 左、右子樹情況不同時,分為node.left 和node.right兩邊討論就行了,第二次見了應該學會了
  • [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

    ? [五分鐘肉眼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 融合二叉树的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。