|
| 1 | +[](https://github.com/javadev/LeetCode-in-All) |
| 2 | +[](https://github.com/javadev/LeetCode-in-All/fork) |
| 3 | + |
| 4 | +## 124\. Binary Tree Maximum Path Sum |
| 5 | + |
| 6 | +Hard |
| 7 | + |
| 8 | +A **path** in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence **at most once**. Note that the path does not need to pass through the root. |
| 9 | + |
| 10 | +The **path sum** of a path is the sum of the node's values in the path. |
| 11 | + |
| 12 | +Given the `root` of a binary tree, return _the maximum **path sum** of any **non-empty** path_. |
| 13 | + |
| 14 | +**Example 1:** |
| 15 | + |
| 16 | + |
| 17 | + |
| 18 | +**Input:** root = [1,2,3] |
| 19 | + |
| 20 | +**Output:** 6 |
| 21 | + |
| 22 | +**Explanation:** The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6. |
| 23 | + |
| 24 | +**Example 2:** |
| 25 | + |
| 26 | + |
| 27 | + |
| 28 | +**Input:** root = [-10,9,20,null,null,15,7] |
| 29 | + |
| 30 | +**Output:** 42 |
| 31 | + |
| 32 | +**Explanation:** The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42. |
| 33 | + |
| 34 | +**Constraints:** |
| 35 | + |
| 36 | +* The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>. |
| 37 | +* `-1000 <= Node.val <= 1000` |
| 38 | + |
| 39 | +## Solution |
| 40 | + |
| 41 | +```javascript |
| 42 | +/** |
| 43 | + * Definition for a binary tree node. |
| 44 | + * function TreeNode(val, left, right) { |
| 45 | + * this.val = (val===undefined ? 0 : val) |
| 46 | + * this.left = (left===undefined ? null : left) |
| 47 | + * this.right = (right===undefined ? null : right) |
| 48 | + * } |
| 49 | + */ |
| 50 | +/** |
| 51 | + * @param {TreeNode} root |
| 52 | + * @return {number} |
| 53 | + */ |
| 54 | +var maxPathSum = function(root) { |
| 55 | + let max = Number.MIN_SAFE_INTEGER |
| 56 | + |
| 57 | + const helper = (node) => { |
| 58 | + if (node === null) { |
| 59 | + return 0 |
| 60 | + } |
| 61 | + |
| 62 | + // Calculate max sum on the left and right subtrees, avoiding negatives |
| 63 | + const left = Math.max(0, helper(node.left)) |
| 64 | + const right = Math.max(0, helper(node.right)) |
| 65 | + |
| 66 | + // Current path sum including the node |
| 67 | + const current = node.val + left + right |
| 68 | + |
| 69 | + // Update the global max if the current path sum is greater |
| 70 | + max = Math.max(max, current) |
| 71 | + |
| 72 | + // Return the max sum of the path passing through the current node |
| 73 | + return node.val + Math.max(left, right) |
| 74 | + } |
| 75 | + |
| 76 | + helper(root) |
| 77 | + return max |
| 78 | +}; |
| 79 | + |
| 80 | +export { maxPathSum } |
| 81 | +``` |
0 commit comments