leetcode - 617 - 合并二叉树

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

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.left = self.mergeTrees(t1.left, t2.left)
        t1.right = self.mergeTrees(t1.right, t2.right)
        
        return t1

你可能感兴趣的:(leetcode,for,python)