class TreeNode {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function maxPathSum(root) {
let maxSum = -Infinity;
function helper(node) {
if (node === null) return 0;
// Recursively get max path sum from left and right children
const leftMax = Math.max(helper(node.left), 0); // ignore negative sums
const rightMax = Math.max(helper(node.right), 0);
// Calculate max path sum passing through current node
const currentSum = node.val + leftMax + rightMax;
// Update global maxSum if currentSum is higher
maxSum = Math.max(maxSum, currentSum);
// Return max sum path going down from current node
return node.val + Math.max(leftMax, rightMax);
}
helper(root);
return maxSum;
}
// Build tree from dry run example
const root = new TreeNode(10,
new TreeNode(2,
new TreeNode(20),
new TreeNode(1)
),
new TreeNode(10,
null,
new TreeNode(-25,
new TreeNode(3),
new TreeNode(4)
)
)
);
console.log(maxPathSum(root));if (node === null) return 0;
stop recursion at leaf's child
const leftMax = Math.max(helper(node.left), 0);
get max path sum from left child, ignore negative sums
const rightMax = Math.max(helper(node.right), 0);
get max path sum from right child, ignore negative sums
const currentSum = node.val + leftMax + rightMax;
calculate max path sum passing through current node
maxSum = Math.max(maxSum, currentSum);
update global max if current path sum is higher
return node.val + Math.max(leftMax, rightMax);
return max path sum going down from current node