原题链接:Leecode 124. 二叉树中的最大路径和
开始写的很冗长:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int res=INT_MIN;
int dfs(TreeNode* root)
{
if(!root) return 0;
int l=dfs(root->left);
int r=dfs(root->right);
int sum=0;
if(l>=0 && r>=0 )
{
res=max(res,root->val+l+r);
sum=max(l,r);
}
else if(l<=0 && r<=0)
{
res=max(res,root->val);
}
else if(l>=0 && r<=0)
{
res=max(res,root->val+l);
sum=l;
}
else if(r>=0 && l<=0)
{
res=max(res,root->val+r);
sum=r;
}
return sum+root->val;
}
int maxPathSum(TreeNode* root) {
if(!root) return 0;
dfs(root);
return res;
}
};
简化后:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int res=INT_MIN;
int dfs(TreeNode* root)
{
if(!root) return 0;
int l=max(dfs(root->left),0);
int r=max(dfs(root->right),0);
res=max(res,root->val+l+r);
return root->val+max(l,r);
}
int maxPathSum(TreeNode* root) {
if(!root) return 0;
dfs(root);
return res;
}
};