Python -- simple with explaination

  • 0
    def mergeTrees(self, t1, t2):
        # if none for both return none
        if not t1 and not t2:
            return None
        # if missing one, then return the other
        if not t1:
            return t2
        if not t2:
            return t1
        # has both
        root = TreeNode(t1.val + t2.val)
        root.left = self.mergeTrees(t1.left, t2.left)
        root.right = self.mergeTrees(t1.right, t2.right)
        return root

Log in to reply

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