Reputation: 4480
I have done this is c++ because you can pass in a parameter by reference. I am having trouble figuring out how to do this in JavaScript. What do I need to change in my code? My output is 1
this.sizeOfBst = function(){
size = 0;
return sizeHelper(this.root, size);
}
function sizeHelper(node, size){
if(node){
sizeHelper(node.left, size);
size++;
sizeHelper(node.right, size);
}
return size
}
Upvotes: 0
Views: 1534
Reputation: 1498
Numbers cannot be passed by reference in Javascript. Instead, have sizeHelper
return the size and add that size to the total.
function sizeHelper(node) {
if (node) {
return 1 + sizeHelper(node.left) + sizeHelper(node.right);
}
return 0;
}
Then it can be used like
this.sizeOfBst = function() {
return sizeHelper(this.root);
}
Upvotes: 1