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