点击打开链接
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int ans = 0;
int dfs(TreeNode* root)
{
if(!root) return 0;
int left = max(0, dfs(root->left));
int right = max(0, dfs(root->right));
ans = max(ans, left+root->val+right);
return root->val+max(left, right);
}
int maxPathSum(TreeNode* root) {
ans = INT_MIN;
dfs(root);
return ans;
}
};
![](https://i-blog.csdnimg.cn/blog_migrate/072d4c4471fe98ce7f82978b78baa77b.png)