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
.
maxx求的是以当前节点为跟节点的时候的最优解,也就是路径是从一个子节点出发到经过跟节点到达另一个子节点,和以根节点出发的情况下最优解。
返回值表示以当前节点为叶子节点时,这条路径的最优解,因此只能选择其中一条最优的路径。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
int i=0,maxx;
class Solution {
public:
int maxPathSum(TreeNode *root) {
if(root==NULL)return 0;
int v1,v2;
if(i==0)maxx=INT_MIN;
++i;
v1=maxPathSum(root->left);
v2=maxPathSum(root->right);
--i;
if(root->val+v1+v2>maxx)maxx=root->val+v1+v2;
if(i==0)return maxx;
return root->val+max(v1,v2)>0?root->val+max(v1,v2):0;
}
};