呓语Beta 2.0 首页 镜头后 灶台前 捐赠者名单 有趣的小站

leetcode 617 Merge Two Binary Trees

文档信息

leetcode 617 Merge Two Binary Trees

解法一

# 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):
    """
    :type t1: TreeNode
    :type t2: TreeNode
    :rtype: TreeNode
    """
    if not t1 and not t2: # t1和t2都是None则返回None
        return None
    ans = TreeNode((t1.val if t1 else 0) + (t2.val if t2 else 0)) # 如果t1和t2有值则使用,否则值为0,再将t1和t2相加
    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

note

捐赠支持

可以使用支付宝转帐给richard.ma.19850509#gmail.com(请将#替换为@),谢谢!

Fork me on GitHub