链接:https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/
描述:
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
解法:
递归求解,
每一个递归返回两个值,一个值是以该节点为根的树中的最大和,另一个值是一该节点为某一起始点的最大路径。
此题思路需要十分清晰,容易出错。另注意树中含有负数的情况。
代码如下:
int maxPathSum(TreeNode *root) {
if(root == NULL) return 0;
if(root->left == NULL && root->right == NULL) return root->val;
int result = 0;
maxSum(root, result);
return result;
}
int maxSum(TreeNode* root, int &maxsum)
{
if( root == NULL) {
maxsum = INT_MIN;
return 0;
}
int leftsum = INT_MIN, rightsum = INT_MIN;
int left = maxSum(root->left, leftsum);
int right = maxSum(root->right, rightsum);
int sum = root->val;
if( left > 0)
sum += left;
if(right > 0)
sum += right;
maxsum = max(leftsum, rightsum);
maxsum = max(maxsum, sum);
return max(left, right) > 0 ? max(left, right) + root->val : root->val;;
}