提也不怎么难,马虎了好几次,剑指offer上有类似的找最大和,那题是找叶子节点,这题是任意的节点,反正就是求和,一样的方法。
int maxPathSumRecursive(TreeNode *root,int &maxsumtoroot)
{
if(root==NULL)
{
maxsumtoroot = INT_MIN;
return INT_MIN;
}
int leftmaxsum=INT_MIN,rightmaxsum=INT_MIN;
int leftsumtoroot=INT_MIN,rightsumtoroot=INT_MIN;
if (root->left)
leftmaxsum = maxPathSumRecursive(root->left,leftsumtoroot);
if(root->right)
rightmaxsum = maxPathSumRecursive(root->right,rightsumtoroot);
int temp;
temp = leftsumtoroot>rightsumtoroot?leftsumtoroot:rightsumtoroot;
if(temp>0)
maxsumtoroot = root->val + temp;
else
maxsumtoroot = root->val;
int sum=root->val;
if(leftsumtoroot>0)
sum += leftsumtoroot;
if(rightsumtoroot>0)
sum += rightsumtoroot;
temp = leftmaxsum>rightmaxsum?leftmaxsum:rightmaxsum;
return max(sum,temp);
}
int maxPathSum(TreeNode *root) {
if(root==NULL)
return 0;
int maxdepthsum;
return maxPathSumRecursive(root,maxdepthsum);
}

本文介绍了一种求解二叉树中最大路径和的递归算法,该算法不仅适用于叶子节点到根节点的最大和路径,也适用于任意节点间的路径。通过递归地计算左右子树的最大路径和,并与当前节点值结合来更新最大路径和。
540

被折叠的 条评论
为什么被折叠?



