题解 | #合并二叉树#

合并二叉树

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

全部评论

相关推荐

10-09 22:05
666 C++
找到工作就狠狠玩CSGO:报联合国演讲,报电子烟设计与制造
点赞 评论 收藏
分享
牛舌:如果我不想去,不管对方给了多少,我一般都会说你们给得太低了。这样他们就会给下一个offer的人更高的薪资了。
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务