1. 程式人生 > >17. Merge Two Binary Trees 融合二叉樹

17. Merge Two Binary Trees 融合二叉樹

col number bug use .com info ber cor tree

[抄題]:

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() Space complexity: O()

[英文數據結構或算法,為什麽不用別的數據結構或算法]:

[關鍵模板化代碼]:

[其他解法]:

[Follow Up]:

[LC給出的題目變變變]:

[代碼風格] :

17. Merge Two Binary Trees 融合二叉樹