原题是这样的
链接:https://leetcode.com/problems/merge-two-binary-trees/#/description
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
中文意思大概是:两个二叉树,把它两重叠起来,如果碰上相同不位两个叶子不为空,就把两个值加起来,如果其中一个为空,则值为另外一个不为空的
python 中
一条语句,a and b 如果 a 不为空,则继续检查b,如果a为空那么直接返回 fasle
a or b 若a不为空,直接返回a,否则继续检查下一个
(a if 1 else b) 利用这样的句式可以简化代码(原来都在lambda中用,发现直接用也可以 比如 f=lambda x:a if 1 else 0)
题中预先给了一个定义
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
该题解答就变成了
class Solution(object):
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
思路很简单,按照先序递归(不懂请百度先序遍历。。。),写python 重点是效率拉。