Accepted C++ solution


  • 0
    F
    class Solution {
    public:
        int ma_val;
        Solution():ma_val(INT_MIN){}
        int helper(TreeNode* root){
            if(root==NULL) return INT_MIN;//means meeting NULL
            int left=helper(root->left);//caculate the ma_val of left tree
            int right=helper(root->right);
            int re=(left>0?left:0)+(right>0?right:0)+root->val;//caculate ma_val go throught 'root'
            ma_val=max(ma_val,max(left,max(right,max(re,root->val))));//update ma_val
            int temp=max(root->val+(left>INT_MIN?left:0),max(root->val+(right>INT_MIN?right:0),root->val));//return the max value of left or right or root to the previous recursion
            return temp>INT_MIN?temp:INT_MIN;
        }
        int maxPathSum(TreeNode* root) {
            if(root->left==NULL&&root->right==NULL)
                return root->val;
            helper(root);
            return ma_val;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.