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) {}
 * };
 */
 #define neg -10000
 struct Node
 {
     int val1;
     int val2;
     Node():val1(neg),val2(neg){};
 };
 
class Solution {
public:
    Node maxPath(TreeNode *root )
    {
        Node result;
        
        if(root->left == NULL && root->right == NULL)
        {
            result.val1=result.val2=root->val;
            return result;
        }
        Node LN;
        Node RN;
        
        if( root->left != NULL)
        {
          LN=maxPath(root->left);
        }
        
        if( root->right != NULL )
        {
           RN=maxPath(root->right);
        }
        
        
          int  tmp=max(LN.val1,RN.val1);
            
        
        if( (root->val >0 || root->val < 0) && tmp < 0)
        {
            result.val1=root->val;
        }
        else
        {
            result.val1=root->val + tmp;
        }
        
        result.val2=max(max(max(LN.val2,RN.val2),LN.val1+RN.val1+root->val),result.val1);
        return result;
    }
    int maxPathSum(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        Node result=maxPath(root);
        
        return result.val2;
    }
    
    
   
};

  

posted @ 2013-06-28 20:45  NinaGood  阅读(162)  评论(0编辑  收藏  举报