I am traversing a binary tree, and accumulating the values of visited nodes in an array . Code as follows:
function Node(val) {
this.val = val;
this.left = null;
this.right = null;
}
function recurseArray(node,arr=[]){
if(!node){
return;
}
arr.push(node.val);
console.log(`array at node ${node.val}: ${arr}`);
recurseArray(node.left,arr);
recurseArray(node.right,arr);
}
let n0 = new Node(0);
let n1 = new Node(1);
let n2 = new Node(2);
n0.left = n1;
n0.right = n2;
recurseArray(n0);
I was expecting to get this output:
array at node 0: 0
array at node 1: 0,1
array at node 2: 0,2
because I thought that a copy of the [0] version of the array would get passed separately to the two recurseArray() calls. But actually I get this output:
array at node 0: 0
array at node 1: 0,1
array at node 2: 0,1,2
It seems that instead it's the same pointer getting passed to the recurseArray() calls, so the changes made in the node.left call show up in the node.right call. Explicitly passing a copy using:
let leftCopy = [...arr];
let rightCopy = [...arr];
recurseArray(node.left,leftCopy);
recurseArray(node.right,rightCopy);
gives the desired output, but making a copy of the array at every recursive call is going to give this function a high time and space complexity (N2 for both, i think?). Is there a more memory-efficient way to do this, or is this explicit copying the only way to get the output I need?