Can u tell the error in my code , 99 testcases passed but 18 failed bool helper(TreeNode *root, int targetSum, int &sum){ //base case if (root == NULL) return false; if (root->left == NULL and root->right == NULL and sum+root->val == targetSum){ return true; } else if (root->left == NULL and root->right == NULL and sum+root->val != targetSum){ return false; }
sum += root->val; bool left = helper(root->left, targetSum, sum); bool right = helper(root->right, targetSum, sum); if (left or right) return true; return false;
}
bool hasPathSum(TreeNode* root, int targetSum) { int sum = 0; return helper(root, targetSum, sum); }
Pass the sum by value instead of reference. Then all the testcases should pass. Sum is always getting incremented between the calls if you pass it by reference. Just change bool helper(TreeNode *root, int targetSum, int &sum){ to bool helper(TreeNode *root, int targetSum, int sum){
Good explanation, thank you!
Glad you enjoyed it!
Can u tell the error in my code , 99 testcases passed but 18 failed
bool helper(TreeNode *root, int targetSum, int &sum){
//base case
if (root == NULL) return false;
if (root->left == NULL and root->right == NULL and sum+root->val == targetSum){
return true;
}
else if (root->left == NULL and root->right == NULL and sum+root->val != targetSum){
return false;
}
sum += root->val;
bool left = helper(root->left, targetSum, sum);
bool right = helper(root->right, targetSum, sum);
if (left or right) return true;
return false;
}
bool hasPathSum(TreeNode* root, int targetSum) {
int sum = 0;
return helper(root, targetSum, sum);
}
Pass the sum by value instead of reference. Then all the testcases should pass.
Sum is always getting incremented between the calls if you pass it by reference. Just change
bool helper(TreeNode *root, int targetSum, int &sum){
to
bool helper(TreeNode *root, int targetSum, int sum){
@@KnowledgeCenter Thanks sir , it worked