# Question

Formatted question description: https://leetcode.ca/all/124.html

124	Binary Tree Maximum Path Sum

Given a binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.

For example:
Given the below binary tree,

1
/ \
2   3

-1
/  \
2   -3

1
/  \
-2   -3

@tag-tree



# Algorithm

In the recursive function, if the current node does not exist, it directly returns 0.

Otherwise, call the recursive function on its left and right child nodes respectively. Since the path sum may be negative, and it is not supposed to add a negative path sum, so compared with 0, choose the larger one and add a positive number.

Then to update the global maximum result res, which is the sum of the maximum path ending at the left child node plus the sum of the maximum path ending at the right child node, plus the current node value, which is a complete path.

The return value is the larger value of left and right plus the value of the current node. Because the return value is defined as the sum of the path ending at the current node, only the larger value of left or right can be used. Not both.

### Notes

The key is to judge well, the maximum value is 4 situations in total

1. left + root + right
2. left + root
3. right + root
4. root

It is to judge which is negative, if left and right child is negative, then discard it to 0 Compare with max

• left+right+root,
• Still root,
• Or root+left,
• Or root+right

The final return is

• Look at root,
• Or root+left,
• Or root+right

Note that the max comparison is to add up both left and right, but when returning, it can only be either the left or the right

Java