Concise python solution


  • 0
    Y
    def maxPathSum(self, root):
        if not root:
            return 0
    
        return max(self.max_path_sum_help(root))
    
    
    def max_path_sum_help(self, root):
        if not root:
            return None
    
        left = self.max_path_sum_help(root.left)
        right = self.max_path_sum_help(root.right)
    
        first = root.val
        second = root.val
        if left:
            first = max(first, root.val + left[0])
            second = max(second, left[1], root.val + max(left[0], 0))
        if right:
            first = max(first, root.val + right[0])
            second = max(second, right[1], root.val + max(right[0], 0) + (left[0] if left and left[0] > 0 else 0))
        return (first, second)

Log in to reply
 

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