LeetCode_Binary Tree Maximum Path Sum

/**

 * 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 getMax(TreeNode *root){

    

        if(root == NULL) return 0;

        int left = getMax(root->left);

        int right = getMax(root->right);

        

        //左子树经过当前节点到右子树的路径

        int cur = root->val ;

        if(left > 0 ) cur += left;

        if(right > 0) cur += right;

        res = res < cur ? cur : res;

        

        int up = left > right ? left : right;

        up = up > 0 ? up  : 0;   

        return up + root->val;

    }

    int maxPathSum(TreeNode *root) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

        if(NULL == root) return 0;

        res = root->val;

        getMax(root);

        return res;

    }

private:

    int res;

};

 

你可能感兴趣的:(LeetCode)