I was trying to complete this question on leetcode and I found a solution. Everything here makes sense to me except the part where they destructure the path array as "[...path]". Can someone explain to me why we wouldn't just pass it as a regular array?
Thank you in advance.
https://leetcode.com/problems/path-sum-ii/
var pathSum = function(root, targetSum, sum = 0, path = [], result = []) {
if(!root) return result;
sum += root.val;
path.push(root.val)
if(!root.left && !root.right){
if(sum === targetSum){
result.push([...path])
} else {
path.pop()
}
}
pathSum(root.left, targetSum, sum, [...path], result)
pathSum(root.right, targetSum, sum, [...path], result)
return result;
};
In JavaScript, variables contain references to arrays, not the whole array. An assignment
path1 = path;
copies the reference, not the array. Both variables contain the same reference to the same array. Modifying path1
also modifies path
.
The expression
[...path]
creates a shallow copy of path. This is required in this code to avoid modifications of the same array on different recursion steps. Each recursive call gets its own copy of the path.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.