天天看點

binary-tree-maximum-path-sum

題目描述

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:

Given the below binary tree,

1
      / \
     2   3
      

Return6.

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