Binary Tree Maximum Path Sum

Solution Code
Definition for a binary tree node.class TreeNode:def init(self, val=0, left=None, right=None):self.val = valself.left = leftself.right = rightclass Solution:def maxPathSum(self, root: Optional[TreeNode]) -> int:self.max_sum = float('-inf')def max_gain(node):
        if not node:
            return 0
        
        # Max sum on the left and right subtrees (ignore negative sums)
        left_gain = max(max_gain(node.left), 0)
        right_gain = max(max_gain(node.right), 0)
        
        # Price of the path at current sub-tree
        current_path_sum = node.val + left_gain + right_gain
        
        # Update global maximum sum
        self.max_sum = max(self.max_sum, current_path_sum)
        
        # Return the max gain if we continue through this node to the parent
        return node.val + max(left_gain, right_gain)
    
    max_gain(root)
    return self.max_sum

Time Complexity

O(N)

Space Complexity

O(H)