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.
思路:题目说的是合并两个二叉树为一个新的二叉树,两树都有节点的部分相加成为新的节点,单个树有节点的部分复制到新树相应的节点。容易想到的是使用二叉树的递归遍历,遍历两树的所有节点,判断数值并进行相加。既然是递归遍历就需要找到遍历体和出口,不难想到的是当两树全为空时为出口,遍历体函数即为MergeTrees
python知识:
and:如果每一个表达式都不是假的话,那么返回最后一个,因为需要一直匹配直到最后一个。如果有一个是假, 那么返回假。
or:只要有一个表达式不是假的话,那么就返回这个表达式的值。只有所有都是假,才返回假。
其一, 在不加括号时候, and优先级大于or
其二, x or y 的值只可能是x或y. x为真就是x, x为假就是y
第三, x and y 的值只可能是x或y. x为真就是y, x为假就是x
class Solution:
def mergeTrees(self, t1, t2):
if not t1 and not t2: return None
ans = TreeNode((t1.val if t1 else 0)+ (t2.val if t2 else 0))
ans.left = self.mergeTrees(t1 and t1.left,t2 and t2.left)
ans.right = self.mergeTrees(t1 and t1.right,t2 and t2.right)
return ans