传送门: />
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 max=-31;
int maxPathSum1(TreeNode* root){
int mlocal=0,v,v1,v2;
if(root == NULL)
return 0;
v = root->val;
mlocal = v;
v1 = maxPathSum1(root->left);
mlocal = v1+v;
v2 = maxPathSum1(root->right);
mlocal = v1+v+v2;
if(mlocal>max)
max = mlocal;
if(v1>v2)
v=root->val+v1;
else v=root->val+v2;
if(v<0)
return 0;
return v;
}
int maxPathSum(TreeNode* root) {
maxPathSum1(root);
return max;
}
};
阅读(2696) | 评论(0) | 转发(0) |