呓语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

付费支持

由于本网站没有广告和任何形式的收入来源,希望获得您的资助。每篇技术性文章和每期shellcasts视频定价人民币1元,在您付费后可以任意观看和下载。

可以使用支付宝手机钱包扫描下方的二维码进行付款操作或者用支付宝转帐给richard.ma.19850509@gmail.com,谢谢!

Fork me on GitHub