LeetCode - Binary Tree Maximum Path Sum

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxPathSum(TreeNode* root) {
        int res = INT_MIN;
        helper(root, res);
        return res;
    }
    int helper(TreeNode* root, int& res){
        if(!root) return 0;
        int left = max(helper(root->left, res), 0);
        int right = max(helper(root->right, res), 0);
        res = max(res, left+right+root->val);
        return max(left, right)+root->val;
    }
};

Path 构成 = left 弯曲path + root + right弯曲path

猜你喜欢

转载自blog.csdn.net/real_lisa/article/details/83049117