题解 | #合并二叉树#
合并二叉树
https://www.nowcoder.com/practice/7298353c24cc42e3bd5f0e0bd3d1d759
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param t1 TreeNode类 # @param t2 TreeNode类 # @return TreeNode类 # class Solution: def merge(self,t1: TreeNode, t2: TreeNode): t1.val += t2.val if t1.left is None and t2.left: # t1没左t2有左 t1.left = t2.left elif t1.left and t2.left: # 都有左,进入递归 self.merge(t1.left, t2.left) # 都没左,不动就行 # 右边同理 if t1.right is None and t2.right: t1.right = t2.right elif t1.right and t2.right: self.merge(t1.right, t2.right) def mergeTrees(self,t1: TreeNode, t2: TreeNode): if t1 is None: return t2 if t2 is None: return t1 self.merge(t1,t2) return t1