Heyy, I have written the same code as dicussed in video but when i tried to submit it on leetcode, it shows wong answer for negative values.
class Solution {
class pair
{
public:
int maxsum=0;
int branchsum=0;
};
pair find(TreeNode* root)
{
pair p;
if(root==NULL)
return p;
pair l=find(root->left);
pair r=find(root->right);
int op1=root->val;
int op2=l.branchsum+root->val;
int op3=r.branchsum+root->val;
int op4=l.branchsum+r.branchsum+root->val;
int current_root_ans=max(op1,max(op2,max(op3,op4)));
p.branchsum=max(l.branchsum,max(r.branchsum,0))+root->val;
p.maxsum=max(l.maxsum,max(r.maxsum,current_root_ans));
return p;
}
public:
int maxPathSum(TreeNode* root) {
if(root->left==NULL && root->right==NULL) return root->val;
pair p=find(root);
return p.maxsum;
}
};
Please check and correct the code