C++
class Solution {
public:
int maxPathSum(TreeNode* root) {
int res = INT_MIN;
helper(root, res);
return res;
}
int helper(TreeNode* root, int& res){
if(!root) return 0;
int left = max(helper(root->left, res), 0);
int right = max(helper(root->right, res), 0);
res = max(res, left+right+root->val);
return max(left, right)+root->val;
}
};
1. Path 构成 = left 弯曲path + root + right弯曲path
2. 并且利用max(, 0)来handle negative number的情况
Python
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
res = float('-inf')
def helper(root):
nonlocal res
if not root: return 0
leftM = helper(root.left)
rightM = helper(root.right)
res = max(res, leftM + rightM + root.val)
return max(0, root.val + max(leftM, rightM))
helper(root)
return res