'Leetcode 112. Path Sum wrong answer for testcases

I am working on Leet code problem 112. Path Sum:

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

When executing my code with this test:

[2,0]
targetSum = 0

...the result is true, but the expected result is false.

It seems to run via root->left, and when the final targetSum != Sum, it will run a recursion, it will run to root->NULL, and the result should be 0. But the result I get is not what I expected...

I don't know how to modify this program?

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *   
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

bool checkhasPath(struct TreeNode* root,int targetSum,int sum){
    sum += root->val;
    count++;
   
    if(root == NULL) return 0;
    if((sum == targetSum) && (!root->left && !root->right)) return 1;
        
    bool res1, res2;
    if(root->left)
        res1 = checkhasPath(root->left,targetSum,sum);
    if(root->right)
        res2 = checkhasPath(root->right,targetSum,sum);
    return res1 || res2;
}

bool hasPathSum(struct TreeNode* root, int targetSum){   
    return checkhasPath(root,targetSum,0);
}


Solution 1:[1]

Two issues:

  • res1 and res2 are uninitialised. When the if conditions are false, they don't get a value other than the undefined value they started with.

  • The check root == NULL should be done before evaluating root->val.

So:

bool checkhasPath(struct TreeNode* root,int targetSum,int sum){
    if(root == NULL) return 0; // do this first
    
    sum += root->val;

    if((sum == targetSum) && (!root->left && !root->right)) return 1;
    
    bool res1 = 0, res2 = 0;  // initialise
    if(root->left)
        res1 = checkhasPath(root->left,targetSum,sum);
    if(root->right)
        res2 = checkhasPath(root->right,targetSum,sum);
    
    return res1 || res2;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 trincot