124. Binary Tree Maximum Path Sum

path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.

The path sum of a path is the sum of the node's values in the path.

Given the root of a binary tree, return the maximum path sum of any non-empty path.


Note: Using max_sum[] as an 1 length array allows to use the variable
globally. Otherwise we need to use nonlocal.


def maxPathSum(root):

    def max_gain(node):
   
        if not node:
            return 0
       
        max_left_gain = max(max_gain(node.left), 0)
        max_right_gain = max(max_gain(node.right), 0)
       
        max_through_down   = node.val + max(max_left_gain, max_right_gain)            
        max_through_across = node.val + max_left_gain + max_right_gain
                   
        max_sum[0] = max(max_sum[0], max_through_across)
               
        return max_through_down

    max_sum = [-math.inf]

    max_gain(root)

Comments

Popular posts from this blog

347. Top K Frequent Elements

849. Maximize Distance to Closest Person

674. Longest Continuous Increasing Subsequence