Lie completely within one subtree (left or right), or
Pass through the current node, combining contributions from both the left and right subtrees.
To compute this maximum, perform a post-order traversal, which allows us to evaluate the left and right subtrees first, then compute the combination at the current node.
Goal: Maintain a global variable (max_sum in Python and maxSum in Java) to store the maximum path sum encountered so far, which may include contributions from both left and right subtrees via the root or stay entirely within one subtree.
Create a global variable max_sum (Python) or maxSum (Java) and initialise it to the smallest possible integer value (float('-inf') in Python or Integer.MIN_VALUE in Java). This will hold the maximum path sum encountered during traversal.
Post-order Traversal:
Traverse the tree in post-order: Starting from the root, process the left and right subtrees before evaluating the current node.
Local Computation at Each Node:
For each node:
Compute the maximum path sum for the left and right subtrees recursively.
If the current node has both left and right children, calculate a candidate path sum passing through the current node: candidate_sum = left_sum + right_sum + node.val
Update the global max_sum if candidate_sum exceeds the current max_sum.
Return the maximum path sum that can be extended upwards: return max(left_sum, right_sum) + node.val
Final Value:
At the end of the traversal, max_sum contains the maximum path sum from one leaf node to another.
classSolution:
def __init__(self):
self.max_sum = float('-inf')
# Function to calculate the maximum path sum from leaf to leafdefmaxPathSum(self, root):
defhelper(node):
ifnot node:
return0# If current node is a leaf nodeifnot node.left andnot node.right:
return node.val
# Recursive calls to left and right subtrees left_sum = helper(node.left) if node.left else float('-inf')
right_sum = helper(node.right) if node.right else float('-inf')
# Update the global maximum when left and right existif node.left and node.right:
self.max_sum = max(self.max_sum, left_sum + right_sum + node.val)
# Return max path sum for the current node's subtreereturn max(left_sum, right_sum) + node.val
helper(root)
return self.max_sum if self.max_sum != float('-inf') else root.val