Binary Tree Maximum Path Sum

从底向上

返回值是当前连续的最大值

m是当前所有的最大值

 

class Solution {
public:
    int m=INT_MIN;
    int maxPath(TreeNode* root)
    {
     if(root==NULL)
        return 0;
        int value=0,lmax=0,rmax=0;
        value=root->val;
        if(root->left)
        {
            lmax=maxPath(root->left);
            if(lmax>0)
            value+=lmax;
        }
        if(root->right)
        {
            rmax=maxPath(root->right);
            if(rmax>0)
            value+=rmax;
        }
        if(value>m)m=value;
        return max(lmax,rmax)>0?max(lmax,rmax)+root->val:root->val;
        }
    int maxPathSum(TreeNode* root) {
        if(root==NULL) 
        return 0;
        maxPath(root);
        return m;
        
    }
};

 

posted on 2016-04-19 22:28  RenewDo  阅读(104)  评论(0编辑  收藏  举报

导航