Search code examples
javascriptrecursiondepth-first-search

Incrementing variable passed into my javascript recursive calls refusing to update


I'm trying to solve leetcode 112.Path Sum. I pass in currSum as 0 initially and want to increment currSum value by adding previous currSum value to current root.val - but currSum is not increasing, see code below:

var hasPathSum = function(root, targetSum) {
    var result = helper(root, targetSum, 0);
    return result;
};

function helper(root, targetSum, currSum){
    if(root === null) return false;

    currSum = currSum + root.val;
    console.log(currSum);

    if(root.left === null && root.right === null && currSum === targetSum){
        return true;
    }

    return hasPathSum(root.left, targetSum, currSum) || hasPathSum(root.right, targetSum, currSum);
}

can someone please point me to what i am doing wrongly. Thanks in advance.

See link to the problem statement here https://leetcode.com/problems/path-sum/

What i expect currSum to be is: 5 9 20 27 22 ...

but what i get is: 5 4 11 7 2 8 13 4 1

Observe that it is just printing back the current root.val at each recursive call.


Solution

  • Whenever you call this function

    var hasPathSum = function(root, targetSum) {
        var result = helper(root, targetSum, 0);
    

    It will call helper with last parameter as zero and it only accepts two parameters - root and targetSum

    Therefore when you call at the end of function

    hasPathSum(root.left, targetSum, currSum)
    

    The currSum is not used in any way, it is just lost

    I have not checked the logic itself, but to keep the currSum value you need to use it in this way:

    return helper(root.left, targetSum, currSum) || helper(root.right, targetSum, currSum);