参考:
思路参考:
https://blog.youkuaiyun.com/huaweidong2011/article/details/82875485
https://blog.youkuaiyun.com/this_is_qiqi/article/details/77859419
class Solution {
int sum;
public:
int maxPathSum(TreeNode* root) {
sum=INT_MIN;
help(root);
return sum;
}
/*** return the max-value-ended-at-root-node ***/
int help(TreeNode* root){ //返回以root节点为结尾的最大值,以root为结尾可以保证不分叉(即加上父节点后还是一条路径)
if(!root) return 0;
int left = max(0, help(root->left)); //左边不分叉路径最大和
int right = max(0, help(root->right)); //右边不分叉路径最大和
/*** key parts : embedding the max-value-find in the recursion process ***/
sum = max(sum, left+right+root->val); //以当前节点为根节点的路径最大和
/*** get the max-value-ended-at-root ***/
return max(left, right)+root->val; //返回以当前节点为结尾的不分叉路径最大和
}
};
分析1
给定一个非空节点,最终路径经过这个节点有4种情况:1.只有该节点本身(左右子树的路径都是负数);2.该节点+左子树路径;3.该节点+右子树路径;4.该节点+左子树路径+右子树路径。其中1,2,3都可以作为子树路径和向上延伸,而4则不行。
分析2
1.如果这个节点是空,则返回值为0;
2.遍历节点的左子树和右子树,将左子树的最大不分叉路径(大于0)+右子树的最大不分叉路径(大于0)+节点本身的值
与当前最大路径和Max作比较,将较大的数保存于Max;
3.返回左右节点的中较大不分叉路径和(大于零)+节点值,作为递归调用。
红色表示路径,右图对于2节点来说,因为其返回的包含左右子树,所以会分叉,则加上父节点1后不会形成路径。而左图中节点2只包含左子树,因此加上父节点1后还是可以构成一条路径