码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode.617 合并两个二叉树

时间:2019-12-30 09:14:14      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:process   otherwise   new   递归   rom   out   tar   use   bsp   

题目描述:给予两个二叉树  t1 , t2  ,合并他们。  

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.

 

思路:

1、输入t1 t2,判断是否都为null  ,如果是 则返回null

2、判断 t1 t2 是否都不为null  ,如果是 则 t1.val += t2.val

3、否则判断 t1 == null && t2 != null ,如果是 则 t1 = new TreeNode(t2.val)

4、如果 t2 !=null 那么说明t2可能还有子节点可以合并到 t1 ,于是进行递归

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

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

5、返回t1

每次递归都是只针对一个节点的合并

 

完整代码:

/**
 * 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) {
        
        // 思路
        // 1. 输入t1 t2 判断是否都为null,如果是则返回null
        // 2. 如果t1 t2 都不为null  那么t1.val += t2.val
        // 3. 如果t1 == null  t2!=null 那么就在t1创建一个节点,值为t2.val
        // 4. 如果t2 !=null 那么就进行递归, 
        //    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;
        
        
        
    }
}

 

leetcode.617 合并两个二叉树

标签:process   otherwise   new   递归   rom   out   tar   use   bsp   

原文地址:https://www.cnblogs.com/smallone/p/12117869.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!