617. Merge Two Binary Trees

You are given two binary trees root1 and root2.

The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.

Return the merged tree.

 

Example:



def mergeTrees(root1: Optional[TreeNode], root2: Optional[TreeNode]):
       
    if root1 is None and root2 is None:
        return None

    v1, left1, right1 = (0, None, None) if root1 is None else (root1.val, root1.left, root1.right)
    v2, left2, right2 = (0, None, None) if root2 is None else (root2.val, root2.left, root2.right)

    newRoot = TreeNode(v1 + v2)

    newRoot.left = mergeTrees(left1, left2)
    newRoot.right = mergeTrees(right1, right2)

    return newRoot 

Comments

Popular posts from this blog

347. Top K Frequent Elements

849. Maximize Distance to Closest Person

674. Longest Continuous Increasing Subsequence