-1

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;        
    }
};
anfjnlnl
  • 63
  • 7

3 Answers3

1

Here is a simple intuitive solution for Path Sum Leetcode

class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {
        if(!root) return false;
        if(!root->right && !root->left) return root->val==sum;
        return hasPathSum(root->left, sum-root->val) ||
               hasPathSum(root->right, sum-root->val);
    }
};
Nilesh Das
  • 9
  • 1
  • 3
0

The code works fine and the logic is perfect, you forgot to put brackets to the if statement

        if(root->left == NULL && root->right == NULL) {
            flag=true;
            return;
        }
 

Here's the full code

class Solution {
public:
    bool flag = false;
    void dfs(TreeNode *root, int currSum, int targetSum){
        if(root == NULL) return ;
        currSum += root->val;
        if(currSum == targetSum) {
            if(root->left==NULL && root->right==NULL) {
                flag=true;
                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;        
    }
};
Rajath Pai
  • 59
  • 2
0
if(root->left==NULL && root->right==NULL) flag=true;
return;

This is wrong. You will return even if the condition doesn't satisfy. As there are negative values, it might be possible that the sum becomes targetSum again at a leaf node after further operations.

Correct:

if(root->left==NULL && root->right==NULL){
    flag = true;
    return;
}
Staz
  • 348
  • 1
  • 2
  • 6