1. 程式人生 > >【兩次過】Lintcode 1126. 合併兩棵二叉樹

【兩次過】Lintcode 1126. 合併兩棵二叉樹

給出兩個二叉樹,並想象當你把其中一個覆蓋另一個時,兩棵樹的一些節點重疊,而其他節點則不重疊。

您需要將它們合併到一個新的二叉樹中。 合併規則是,如果兩個節點重疊,則將節點值加起來作為合併節點的新值。 否則,非空節點將用作新樹的節點。

樣例

輸入: 
	樹 1                     樹 2                  
          1                         2                             
         / \                       / \                            
        3   2                     1   3                        
       /                           \   \                      
      5                             4   7                  
輸出: 
合併的樹:
	     3
	    / \
	   4   5
	  / \   \ 
	 5   4   7

注意事項

合併過程必須從兩個樹的根節點開始。


解題思路:

前序遍歷,依次相加即可。

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param t1: the root of the first tree
     * @param t2: the root of the second tree
     * @return: the new binary tree after merge
     */
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        // Write your code here
        if(t1==null && t2==null)
            return null;
        else if(t1 == null)
            return t2;
        else if(t2 == null)
            return t1;
        
        //兩者都不為空,則疊加
        t1.val += t2.val;
        t1.left = mergeTrees(t1.left, t2.left);
        t1.right = mergeTrees(t1.right, t2.right);
        
        return t1;
    }
}