Skip to content

Commit 1600c3b

Browse files
authored
Merge pull request neetcode-gh#525 from kciccolella/leetcode124
Create 124-Binary-Tree-Maximum-Path-Sum.js
2 parents 3ae16b0 + e9e0573 commit 1600c3b

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {TreeNode} root
11+
* @return {number}
12+
*/
13+
var maxPathSum = function(root) {
14+
const res = [root.val];
15+
16+
// return max path sum without split
17+
function dfs(root) {
18+
if (!root) {
19+
return 0;
20+
}
21+
22+
let leftMax = dfs(root.left);
23+
let rightMax = dfs(root.right);
24+
leftMax = Math.max(leftMax, 0);
25+
rightMax = Math.max(rightMax, 0);
26+
27+
// compute max path sum WITH split
28+
res[0] = Math.max(res[0], root.val + leftMax + rightMax);
29+
30+
return root.val + Math.max(leftMax, rightMax);
31+
}
32+
33+
dfs(root);
34+
return res[0];
35+
};

0 commit comments

Comments
 (0)