艾恩凝
个人博客 https://aeneag.xyz/
公众号 技术乱舞
每日一练,保持手感
2021/10/18
题目
https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/
分析
递归,左右子树分开,然后合并
题解
class Solution {
public:
int max_sum = -10000 ;
int dfs(TreeNode* node){
if(!node)return 0;
int left = max(dfs(node->left),0);
int right = max(dfs(node->right),0);
max_sum = max(max_sum,node->val+left+right);
return node->val + max(left,right);
}
int maxPathSum(TreeNode* root) {
dfs(root);
return max_sum;
}
};