题目:
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
.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxPathSumCore(TreeNode *root, int &maxSum){//返回值表示从root到其任意子节点的最大距离,maxSum表示在遍历过程中以当前节点为最高层节点时最大的路径长度,采用后序遍历
if (NULL == root) return INT_MIN;
int sum = root->val;
int ll = 0, rr = 0;
int res = root->val;
if (root->left != NULL){
ll = maxPathSumCore(root->left, maxSum);
if (ll + root->val > res) res = ll + root->val;
}
if (root->right != NULL){
rr = maxPathSumCore(root->right, maxSum);
if (rr + root->val > res) res = rr + root->val;
}
if (ll > 0) sum += ll;
if (rr > 0) sum += rr;
if (sum > maxSum) maxSum = sum;
return res;
}
int maxPathSum(TreeNode* root) {
if (NULL == root) return 0;
int maxSum = root->val;
maxPathSumCore(root, maxSum);
return maxSum;
}
};