They are but only at that point, Arrays are passed around by reference , so any change you do the same slate instance as it gets passed around up and down the tree(future push /pop ) are also reflected into the result . You want your hard earned path solutions to be snapshots in time and remain intact . If you don't copy the array , the same address in memory gets passed around and your data will get corrupt.
Hey Andy,
Why did we do slate.slice() on line 23. Wouldn't slate and slate.slice() be the same thing as both will returns the array only.
They are but only at that point, Arrays are passed around by reference , so any change you do the same slate instance as it gets passed around up and down the tree(future push /pop ) are also reflected into the result . You want your hard earned path solutions to be snapshots in time and remain intact . If you don't copy the array , the same address in memory gets passed around and your data will get corrupt.
that's also an alternative line " paths.push([...slate])"
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} targetSum
* @return {number[][]}
*/
var pathSum = function(root, targetSum) {
if(!root) return [];
const paths=[];
const dfs = (node, sum, slate) => {
if(node.left === null && node.right === null){
if(sum === node.val){
slate.push(node.val);
paths.push(slate.slice());
slate.pop();
}
}
if(node.left){
slate.push(node.val);
dfs(node.left, sum - node.val, slate);
slate.pop();
}
if(node.right){
slate.push(node.val);
dfs(node.left, sum - node.val, slate);
slate.pop();
}
}
dfs(root, targetSum, []);
return paths;
};;