思路:

1. 对于每一个节点, 返回其所在子树所能提供的最大值, 且该最大值必须是单支的, WA 过

2. max(0, max(lf, rt))+root->val, 可以仅返回根节点, WA 过

3. 需要维护一个全局最优解 ans, WA 过

代码:

class Solution {
public:
	int ans;
	int solve_dp(TreeNode *root) {
		if(root == NULL)
			return 0;

		int sum = root->val;
		int lf = 0, rt = 0;
		if(root->left)
		lf = solve_dp(root->left);
		
		if(root->right) 
		rt = solve_dp(root->right);
		if(lf > 0)
			sum += lf;
		if(rt > 0)
			sum += rt;

		ans = max(ans, sum);
		return max(0, max(lf, rt))+root->val;
	}
    int maxPathSum(TreeNode *root) {
		ans = -100000000;
		solve_dp(root);
		return ans;
    }
};

  

相关文章:

  • 2022-02-24
  • 2021-07-16
  • 2022-01-26
  • 2021-05-21
猜你喜欢
  • 2021-08-05
  • 2021-09-17
  • 2021-11-12
  • 2021-07-04
  • 2021-05-20
  • 2021-06-27
相关资源
相似解决方案