problem My code fails for the following test case. I don't understand why. Can you tell me where I went wrong? My code passes (114/116) test cases. I'm doing DFS and checking whether currSum==targetSum
and if it satisfies this condition and it's also a leaf node I'm setting global variable ```flag=true``.
[1,-2,-3,1,3,-2,null,-1]
-1
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool flag=false;
void dfs(TreeNode *root, int currSum, int targetSum){
if(root==NULL) return ;
// cout<<currSum<<" ";
currSum+=root->val;
cout<<currSum<<" ";
if(currSum == targetSum) {
if(root->left==NULL && root->right==NULL) flag=true;
return;
}
// else if(abs(currSum)>abs(targetSum)) return;
dfs(root->left,currSum,targetSum);
dfs(root->right,currSum,targetSum);
}
bool hasPathSum(TreeNode* root, int targetSum) {
int currSum=0;
dfs(root,currSum,targetSum);
return flag;
}
};