Aaron Aaron - 27 days ago 19
Javascript Question

Javascript size on binary search tree

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
}

Answer

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);
}
Comments