首先考虑 过单个点的最大路径和 是怎么得到
- 左儿子的最大路径和 + 当前节点最大值 (往上走)
- 右边的最大路径和 + 当前节点最大值 (往上走)
- 左儿子的最大路径和 + 当前节点最大值 + 右儿子最大路径和 (左儿子 + 当前节点+ 右儿子)
- 当前节点最大值,不往下延伸 (有负值,左右都可以负贡献)
定义函数 maxSum[i] 表示过i并且往上走的最大路径和,
case 1、2、4 maxSum(i) = max(max(maxSum[i.left] + i.val , maxSum[i.right] + i.val) , i.val)
case 3 ans(i) = max(maxSum(i), maxSum[i.left] + i.val + maxSum[i.right])
class Solution {
int maxAns = INT32_MIN;
public:
int getMaxPathSum(TreeNode *root) {
int maxValue = root->val;
int maxLeftValue, maxRightValue;
if (root->left != NULL && root->right != NULL) {
maxLeftValue = getMaxPathSum(root->left);
maxRightValue = getMaxPathSum(root->right);
maxAns = max(maxAns, maxLeftValue + maxRightValue + root->val);
maxValue = max(max(maxLeftValue + root->val, maxRightValue + root->val), root->val);
} else if (root->left != NULL) {
maxValue = max(getMaxPathSum(root->left) + root->val, root->val);
} else if (root->right != NULL) {
maxValue = max(getMaxPathSum(root->right) + root->val, root->val);
} else {
maxValue = root->val;
}
cout<<"----"<<maxValue<<endl;
maxAns = max(maxAns, maxValue);
return maxValue;
}
public:
int maxPathSum(TreeNode *root) {
return max(maxAns, getMaxPathSum(root));;
}
};