Path Sum I fastest JS solution (beats 100% on runtime)


  • 0
    O
    var hasPathSum = function(root, sum) {
        if (root === null){
            return false;
        }      
        return pathFind(root, root.val);
        function pathFind(currNode, currSum){ //by our definition currSum must include currNode.val
            if (currNode.left !== null && currNode.right !== null){
              return (pathFind(currNode.left, currSum + currNode.left.val) || pathFind(currNode.right, currSum + currNode.right.val));
            }
            if (currNode.left === null && currNode.right === null){
                if (currSum === sum){ //being at a null point, check for truth
                  return true;
                }
                return false
            }
            if (currNode.left === null){
              return pathFind(currNode.right, currSum + currNode.right.val);
            }
            else {
                return pathFind(currNode.left, currSum + currNode.left.val);
            }
        };
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.