Binary Tree Maximum Path Sum LeetCode solution in JavaScript

1
var maxPathSum = function (root) {
2
let res = -Infinity;
3
function solve(root) {
4
if (!root) {
5
return 0;
6
}
7

8
let left = solve(root.left);
9
let right = solve(root.right);
10
//ignore the values with negative sum
11
let leftVal = Math.max(left, 0);
12
let rightVal = Math.max(right, 0);
13

14
let localMax = leftVal + rightVal + root.val;
15
res = Math.max(localMax, res);
16
return Math.max(leftVal, rightVal) + root.val;
17
}
18
solve(root);
19
return res;
20
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0