| 21 | } |
| 22 | |
| 23 | int maxPathSumHelper(TreeNode* node, int& maxSum) { |
| 24 | // Base case: null nodes have no path sum. |
| 25 | if (!node) |
| 26 | return 0; |
| 27 | // Collect the maximum gain we can attain from the left and right |
| 28 | // subtrees, setting them to 0 if they're negative. |
| 29 | int leftSum = std::max(maxPathSumHelper(node->left, maxSum), 0); |
| 30 | int rightSum = std::max(maxPathSumHelper(node->right, maxSum), 0); |
| 31 | // Update the overall maximum path sum if the current path sum is |
| 32 | // larger. |
| 33 | maxSum = std::max(maxSum, node->val + leftSum + rightSum); |
| 34 | // Return the maximum sum of a single, continuous path with the |
| 35 | // current node as an endpoint. |
| 36 | return node->val + std::max(leftSum, rightSum); |
| 37 | } |