python - merge trees

  • 0
    # 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
            root = None
            if t1 or t2:
                root = TreeNode((t1.val if t1 else 0) + (t2.val if t2 else 0))
                root.left = self.mergeTrees(t1.left if t1 else None, t2.left if t2 else None)
                root.right = self.mergeTrees(t1.right if t1 else None, t2.right if t2 else None)
            return root

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.