/*
* @lc app=leetcode id=124 lang=javascript
*
* [124] Binary Tree Maximum Path Sum
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
function helper(node, payload) {
if (node === null) return 0;
const l = helper(node.left, payload);
const r = helper(node.right, payload);
payload.max = Math.max(
node.val + Math.max(0, l) + Math.max(0, r),
payload.max
);
return node.val + Math.max(l, r, 0);
}
/**
* @param {TreeNode} root
* @return {number}
*/
var maxPathSum = function (root) {
if (root === null) return 0;
const payload = {
max: root.val,
};
helper(root, payload);
return payload.max;
};
Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int ans;
public int maxPathSum(TreeNode root) {
ans = Integer.MIN_VALUE;
helper(root); // recursion
return ans;
}
public int helper(TreeNode root) {
if (root == null) return 0;
int leftMax = Math.max(0, helper(root.left)); // find the max sub-path sum in left sub-tree
int rightMax = Math.max(0, helper(root.right)); // find the max sub-path sum in right sub-tree
ans = Math.max(ans, leftMax+rightMax+root.val); // find the max path sum at current node
return max(leftMax, rightMax) + root.val; // according to the definition of path, the return value of current node can only be that the sum of current node value plus either left or right max path sum.
}
}
Python
class Solution:
ans = float('-inf')
def maxPathSum(self, root: TreeNode) -> int:
def helper(node):
if not node: return 0
l = helper(node.left)
r = helper(node.right)
self.ans = max(self.ans, max(l,0) + max(r, 0) + node.val)
return max(l, r, 0) + node.val
helper(root)
return self.ans
CPP
class Solution {
private:
int ans = INT_MIN;
int postOrder(TreeNode *root) {
if (!root) return INT_MIN;
int L = max(0, postOrder(root->left)), R = max(0, postOrder(root->right));
ans = max(ans, L + R + root->val);
return root->val + max(L, R);
}
public:
int maxPathSum(TreeNode* root) {
postOrder(root);
return ans;
}
};