本题有两个相关问题:1)所求路径可以位于任意两个节点之间(参见leetcode);2)所求路径位于两个叶子节点之间(参见geekforgeeks)。
下面给出问题1)的解法。问题2)的解法可以根据解法1)很容易得出。问题1)的解法:遍历所有节点,求出经过每一个节点的最大路径,最后再求出经过每个节点的最大路径的最大值。用递归的思路,自底向上递归。
下面是代码:
void maxPathSumUtil(Node* root, int& left, int& right, int& maxSum);
int maxPathSum(TreeNode *root) {
// find out the max path sum between any two nodes in a binary tree
int maxSum = -10000;
int left, right;
maxPathSumUtil(root, left, right, maxSum);
return maxSum;
}
void maxPathSumUtil(TreeNode* root, int& left, int& right, int& maxSum)
{
// left will be the max value of a path with root as the right-most node
// right will be the max value of a path with root as the left-most node
// maxSum will be the max path value up until now
if(root==NULL)
{
left = 0;
right = 0;
return;
}
int left1, left2, right1, right2;
// traverse the left subtree
maxPathSumUtil(root->left, left1, right1, maxSum);
// traverse the right subtree
maxPathSumUtil(root->right, left2, right2, maxSum);
// left at least has a value of root->val
// right at least has a value of root->val
left = root->val;
right = root->val;
if(max(left1,right1)<=0 && max(left2,right2)<=0)
{// if so, root will be the starting point of a new path
maxSum = max(root->val, maxSum);
return;
}
if( max(left1,right1)>0 )
{
left = left + max(left1,right1);
}
if( max(left2,right2)>0 )
{
right = right + max(left2,right2);
}
maxSum = max(left+right - root->val, maxSum);
}