您的位置:首页 > 编程语言 > Python开发

python--617 Merge Two Binary Trees

2018-01-23 22:04 429 查看

617. Merge Two Binary Trees

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)如果给定的节点为空,用其相对应的节点代替它

 1)如果与其相对应的节点为空,则用这个节点代替二者的和
 2)如果与其相对应的节点不为空,则将二者加起来,继续考虑该节点的左右子节点
        考虑树的问题,一般要用到递归。

代码

class Solution:
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if t1 is None and t2 is None:
return
# 只有一个结点为空时
if t1 is None:
return t2
if t2 is None:
return t1
# 结点重叠时
t1.val += t2.val
# 进行迭代
t1.right = self.mergeTrees(t1.right, t2.right)
t1.left = self.mergeTrees(t1.left, t2.left)
return t1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: