Skip to content

Commit

Permalink
Merge pull request neetcode-gh#525 from kciccolella/leetcode124
Browse files Browse the repository at this point in the history
Create 124-Binary-Tree-Maximum-Path-Sum.js
  • Loading branch information
Ahmad-A0 authored Jul 18, 2022
2 parents 3ae16b0 + e9e0573 commit 1600c3b
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions javascript/124-Binary-Tree-Maximum-Path-Sum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* 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) {
const res = [root.val];

// return max path sum without split
function dfs(root) {
if (!root) {
return 0;
}

let leftMax = dfs(root.left);
let rightMax = dfs(root.right);
leftMax = Math.max(leftMax, 0);
rightMax = Math.max(rightMax, 0);

// compute max path sum WITH split
res[0] = Math.max(res[0], root.val + leftMax + rightMax);

return root.val + Math.max(leftMax, rightMax);
}

dfs(root);
return res[0];
};

0 comments on commit 1600c3b

Please sign in to comment.