Aaron Aaron - 1 year ago 116
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){
sizeHelper(node.left, size);
sizeHelper(node.right, size);
return size

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download