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;
};

 

posted @ 2013-04-10 10:20  冰点猎手  阅读(127)  评论(0编辑  收藏  举报