/* * @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; * } */functionhelper(node, payload) {if (node ===null) return0;constl=helper(node.left, payload);constr=helper(node.right, payload);payload.max =Math.max(node.val +Math.max(0, l) +Math.max(0, r),payload.max );returnnode.val +Math.max(l, r,0);}/** * @param{TreeNode} root * @return{number} */varmaxPathSum=function (root) {if (root ===null) return0;constpayload= { max:root.val, };helper(root, payload);returnpayload.max;};
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */classSolution {int ans;publicintmaxPathSum(TreeNode root) { ans =Integer.MIN_VALUE;helper(root); // recursionreturn ans; }publicinthelper(TreeNode root) {if (root ==null) return0;int leftMax =Math.max(0,helper(root.left)); // find the max sub-path sum in left sub-treeint 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
classSolution: ans =float('-inf')defmaxPathSum(self,root: TreeNode) ->int:defhelper(node):ifnot node:return0 l =helper(node.left) r =helper(node.right) self.ans =max(self.ans, max(l,0) +max(r, 0) + node.val)returnmax(l, r, 0)+ node.valhelper(root)return self.ans
CPP
classSolution {private:int ans = INT_MIN;intpostOrder(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);returnroot->val +max(L, R); }public:intmaxPathSum(TreeNode* root) {postOrder(root);return ans; }};