Likou 617. Merging binary trees (python)

Title source: 617. Merge binary tree
idea: recursion Using the recursive method, if the left and right nodes exist, the new node is the sum of the left and right nodes, and if not, the existing left and right nodes are returned.
python code:

# 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

            

insert image description here
Reference link: 617. Merge binary tree (python)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324339890&siteId=291194637