LeetCode 617. Merge Two Binary 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

 

Note: The merging process must start from the root nodes of both trees.

 


題目標題:Tree

 

  這道題目給了我們兩個二叉樹,要我們合並兩個二叉樹,合並的樹的每一個點的值等於兩個二叉樹相對位置的點的值的合。利用recursively call來實現,我們來分析一下。對於每一個新的點的值,我們需要做的就是把兩個樹中的同樣位置的點的值相加。然后recursively來繼續代入mergeTrees,左邊的點,就代入同樣位置兩個點的左邊。右邊的點就代入同樣位置的兩個點的右邊,直到代入得兩個點都是null,就停止代入,return回去。 那么對於每一個新的點,有三種情況:1- 兩個點都是null,就直接return; 2- 兩個點都不是null,直接相加;3- 兩個點其中有一個點是null,那么就取另外一個點的值。 需要注意的是,對於每一個新的點,如果代入的兩個點其中一個是null的話,那么這個null的點的 .left 和.right 是error。所以要先initial 一下。

 

Java Solution:

Runtime beats 60.24% 

完成日期:06/29/2017

關鍵詞:Tree

關鍵點:利用recursively來求每一個新的點,以及這個點的左右child

 

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution 
11 {
12     public TreeNode mergeTrees(TreeNode t1, TreeNode t2) 
13     {
14         TreeNode root;
15         TreeNode left_1 = null, left_2 = null;
16         TreeNode right_1 = null, right_2 = null;
17         
18         if(t1 == null && t2 == null)
19             return null;
20         else if(t1 != null && t2 != null)
21         {
22             root = new TreeNode(t1.val + t2.val);
23             left_1 = t1.left;
24             left_2 = t2.left;
25             right_1 = t1.right;
26             right_2 = t2.right;
27         }
28         else if(t1 != null && t2 == null)
29         {
30             root = new TreeNode(t1.val);
31             left_1 = t1.left;
32             right_1 = t1.right;
33         }
34         else
35         {
36             root = new TreeNode(t2.val);
37             left_2 = t2.left;
38             right_2 = t2.right;
39         }
40         
41         
42         root.left = mergeTrees(left_1, left_2);
43         root.right = mergeTrees(right_1, right_2);
44         
45             
46         return root;
47     }
48 }

參考資料:N/A

 

LeetCode 算法題目列表 - LeetCode Algorithms Questions List


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM