Leetcode 124 Binary Tree Maximum Path Sum

75 阅读1分钟

特别有意思的一道题。

我觉得是leetcode hard binary search tree中集大成的一道有趣的题目。

recursive 如何思考,如何实时更新最大的值。以及这道题本身的思考方式。懂了之后特别有意思。算是easy 模式的hard。解题思路清晰不打转

class Solution {
private:
    int path_min = INT_MIN;    
public:
    int maxRoute(TreeNode* root){
        if(root == nullptr) return 0;
        int leftMax = max(maxRoute(root->left), 0);
        int rightMax = max(maxRoute(root->right), 0);
        int tempMax = root->val + leftMax + rightMax;
        path_min = max(path_min, tempMax);
        return max(leftMax, rightMax) + root->val;
    }
    int maxPathSum(TreeNode* root) {
        maxRoute(root);
        return path_min;
    }
};

Leetcode 124 地址

类似思路 easy题: 543. Diameter of Binary Tree

先做这道再去做其他的easy会觉得真是太easy了^_^