| 14 | } |
| 15 | |
| 16 | func maxPathSumHelper(root *TreeNode) int { |
| 17 | if root == nil { |
| 18 | return 0 |
| 19 | } |
| 20 | |
| 21 | // Including the left/right child in the current sum is not optimal |
| 22 | // if either is negative, so take the max of the left/right sum and 0 |
| 23 | leftSum := int(math.Max(float64(maxPathSumHelper(root.Left)), 0.0)) |
| 24 | rightSum := int(math.Max(float64(maxPathSumHelper(root.Right)), 0.0)) |
| 25 | pathSum := rightSum + leftSum + root.Val |
| 26 | max = int(math.Max(float64(max), float64(pathSum))) |
| 27 | |
| 28 | return root.Val + int(math.Max(float64(rightSum), float64(leftSum))) |
| 29 | } |