力扣617.合并二叉树(python)

题目来源: 617.合并二叉树
思路:递归 利用递归的方法,如果左右结点存在,则新结点为左右结点之和,若不存在,则返回存在的左右结点。
python代码:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def mergeTrees(self, root1, root2):
        """
        :type root1: TreeNode
        :type root2: TreeNode
        :rtype: TreeNode
        """
        if root1 != None and root2 != None:
            node = TreeNode(root1.val+root2.val)
            node.left = self.mergeTrees(root1.left, root2.left)
            node.right = self.mergeTrees(root1.right, root2.right)
            return node
        else:
            return root1 if root1 else root2

            

力扣617.合并二叉树(python)_第1张图片
参考链接: 617. 合并二叉树(python)

你可能感兴趣的:(力扣刷题笔记,leetcode,深度优先,算法)