124. Binary Tree Maximum Path Sum

A 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. A node's value can be negative.

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

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxPathSum(self, root: Optional[TreeNode]) -> int:
        self.res = -float('inf')

        # Returns the max path sum that starts from the node and ends with one of its child
        def dfs(node) -> int:
          if not node:
            return 0
          lmax = max(0, dfs(node.left))
          rmax = max(0, dfs(node.right))
          self.res = max(self.res, lmax + rmax + node.val)
          return node.val + max(lmax, rmax)

        dfs(root)
        return self.res