Tree: Depth-First Search - Binary Tree Maximum Path Sum
Examine the following buggy code snippet for computing the maximum path sum in a binary tree. Which line contains the subtle bug that causes incorrect results on trees with negative node values?
def maxPathSum(root):
max_sum = float('-inf')
def max_gain(node):
nonlocal max_sum
if not node:
return 0
left_gain = max_gain(node.left)
right_gain = max_gain(node.right)
current_path_sum = node.val + left_gain + right_gain
max_sum = max(max_sum, current_path_sum)
# Bug: returns sum of both left and right gains to parent
return node.val + left_gain + right_gain
max_gain(root)
return max_sum
