且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[LeetCode] Binary Tree Maximum Path Sum

更新时间:2021-09-15 19:07:52

A relatively difficult tree problem. Well, a recursive solution still gives clean codes. The tricky part of this problem is how to record the result. You may refer to this link for a nice solution. The code is rewritten as follows.

class Solution {
public:
    int maxPathSum(TreeNode* root) {
        sum = INT_MIN;
        pathSum(root);
        return sum;
    }
private:
    int sum;
    int pathSum(TreeNode* node) {
        if (!node) return 0;
        int left = max(0, pathSum(node -> left));
        int right = max(0, pathSum(node -> right));
        sum = max(sum, left + right + node -> val);
        return max(left, right) + node -> val;
    }
};