leetcode.617 merge two binary trees

Description Title: given two binary tree t1, t2, merge them.  

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.

 

Ideas:

1, input t1 t2, determines whether or are null, null is returned if it is

2, t1 t2 is determined whether or not null, and if it is then t1.val + = t2.val

3, and otherwise determine t1 == null && t2! = Null, then if t1 = new TreeNode (t2.val)

4, if t2! = Null then that t2 may also be incorporated into the child node t1, then recursively

      t1.left = mergeTrees(t1.left, t2.left)

      t1.right = mergeTrees(t1.right, t2.right)

5, returned t1

Each recursion is only for a merged node

 

Complete code:

/ ** 
 * A for binary Tree Node Definition. 
 * Public class the TreeNode { 
 * int Val; 
 * the TreeNode left; 
 * the TreeNode right; 
 * the TreeNode (int X) {X = Val;} 
 *} 
 * / 
class Solution {
     public the TreeNode mergeTrees (the TreeNode T1, T2 the TreeNode) { 
        
        // idea
         // 1 determines whether the input t1 t2 are null, null is returned if
         // 2. If not a null then t1 t2 + = t2.val t1.val
         / / 3. If t1 == null t2! = null then create a node t1, the value t2.val
         // 4. If T2! = null then recursively, 
         //     t1.left = mergeTrees (t1.left, t2.left)
         //    t1.right = mergeTrees(t1.right, t2.right)
        // 5. 返回t1
        
        if(t1 == null && t2 == null)
            return null;
        if(t1 != null && t2 != null){
            t1.val += t2.val;
        }else if(t1 == null && t2 != null){
            t1 = new TreeNode(t2.val);
        }
        if(t2 !=null){
            t1.left = mergeTrees(t1.left, t2.left);
            t1.right = mergeTrees(t1.right, t2.right);
        }
        return t1;
        
        
        
    }
}

 

Guess you like

Origin www.cnblogs.com/smallone/p/12117869.html