首页 > 其他 > 详细

LeetCode #617 Merge Two Binary Trees

时间:2017-06-28 21:05:09      阅读:209      评论:0      收藏:0      [点我收藏+]

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 class Solution:
 2     def mergeTrees(self, t1, t2):
 3         """
 4         :type t1: TreeNode
 5         :type t2: TreeNode
 6         :rtype: TreeNode
 7         """
 8         if t1 and t2:
 9             t1.val = t1.val+t2.val
10             t1.left = self.mergeTrees(t1.left, t2.left)
11             t1.right = self.mergeTrees(t1.right, t2.right)
12             return t1
13         elif t1:
14             return t1
15         elif t2:
16             return t2

 

LeetCode #617 Merge Two Binary Trees

原文:http://www.cnblogs.com/lhppom/p/7091592.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!