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
Return6.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxChildPath(TreeNode * root,int& maxx){
if( root == NULL)
return 0;
int x = maxChildPath(root->left,maxx);
int y = maxChildPath(root->right,maxx);
//考虑到节点的值可能为负数;所以必须加以判断。
int z = 0;
if( x>= 0 && y>=0){
z = x + y ;
}
else if( x > 0 || y > 0 ){
z = x>y ? x : y;
}
else{
z = 0;
}
z += root->val;
maxx = max( maxx, z);
return max(x,y)>0 ? max(x,y)+root->val : root->val;
}
int maxPathSum(TreeNode *root) {
if( root == NULL)
return 0;
int maxx = numeric_limits<int> ::min();
maxChildPath( root , maxx);
return maxx;
}
};