struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int maxPathSum(TreeNode *n, int &max) {
if (n == NULL) return 0;
int lSum = maxPathSum(n->left, max);
int rSum = maxPathSum(n->right, max);
int sum = n->val;
int pathSum = 0;
if (lSum > 0) {
sum += lSum;
pathSum += lSum;
}
if (rSum > 0) {
sum += rSum;
if (pathSum < rSum) {
pathSum = rSum;
}
}
if (sum > max) max = sum;
pathSum += n->val;
return pathSum;
}
int maxPathSum(TreeNode *root) {
int max = INT_MIN;
maxPathSum(root, max);
return max;
}