forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJeehay28.js
More file actions
37 lines (29 loc) · 982 Bytes
/
Jeehay28.js
File metadata and controls
37 lines (29 loc) · 982 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// ✅ Time Complexity: O(N) (Each node is visited once)
// ✅ Space Complexity: O(N)
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxPathSum = function (root) {
let maxSum = -Infinity;
const dfs = (node) => {
if (!node) return 0;
let leftMax = Math.max(dfs(node.left), 0);
let rightMax = Math.max(dfs(node.right), 0);
// Compute best path sum that passes through this node
let currentMax = node.val + leftMax + rightMax;
// Update global maxSum
maxSum = Math.max(maxSum, currentMax); // represents the best path sum for the current node.
return node.val + Math.max(leftMax, rightMax); // propagates the maximum path sum to the parent node.
};
dfs(root);
return maxSum;
};