Leetcode: Binary Tree Maximum Path Sum

思路:

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

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

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

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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;
    }
};

  

posted @   SangS  阅读(495)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示