Skip to content

Commit 7104cf7

Browse files
committed
Add binary-tree-maximum-path-sum
1 parent 98df690 commit 7104cf7

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// ✅ Time Complexity: O(N) (Each node is visited once)
2+
// ✅ Space Complexity: O(N)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* function TreeNode(val, left, right) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.left = (left===undefined ? null : left)
9+
* this.right = (right===undefined ? null : right)
10+
* }
11+
*/
12+
/**
13+
* @param {TreeNode} root
14+
* @return {number}
15+
*/
16+
var maxPathSum = function (root) {
17+
let maxSum = -Infinity;
18+
19+
const dfs = (node) => {
20+
if (!node) return 0;
21+
22+
let leftMax = Math.max(dfs(node.left), 0);
23+
let rightMax = Math.max(dfs(node.right), 0);
24+
25+
// Compute best path sum that passes through this node
26+
let currentMax = node.val + leftMax + rightMax;
27+
28+
// Update global maxSum
29+
maxSum = Math.max(maxSum, currentMax); // represents the best path sum for the current node.
30+
31+
return node.val + Math.max(leftMax, rightMax); // propagates the maximum path sum to the parent node.
32+
};
33+
34+
dfs(root);
35+
return maxSum;
36+
};
37+

0 commit comments

Comments
 (0)