1
\$\begingroup\$

Is this an efficient and clean implementation?

function BST(items) {
    this.tree = {};
    if (items) items.forEach(this.add, this);
}

BST.prototype.add = function(item) {
    if (!this.tree.value) {
        this.tree.value = item;
        return item;
    }
    var currNode = this.tree;
    var inserted = false;
    while (!inserted) {
        if (item > currNode.value) {
            if (currNode.rightNode) currNode = currNode.rightNode;
            else {
                currNode.rightNode = {
                    value: item
                };
                inserted = true;
            }
        } else {
            if (currNode.leftNode) currNode = currNode.leftNode;
            else {
                currNode.leftNode = {
                    value: item
                };
                inserted = true;
            }
        }
    }
    return item;
};

BST.prototype.printTree = function() {
    console.log(this.tree);
};
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Interface

Why return the value added? That's unusual and unexpected.

Bug

It's unusual to allow adding duplicate values. It would be better to ignore.

Avoid flag variables when possible

The flag variable inserted is unnecessary.

while (true) {
    if (item > currNode.value) {
        if (currNode.rightNode) currNode = currNode.rightNode;
        else {
            currNode.rightNode = {
                value: item
            };
            return;
        }
    } else {
        if (currNode.leftNode) currNode = currNode.leftNode;
        else {
            currNode.leftNode = {
                value: item
            };
            return;
        }
    }
}

I replaced the insert = true statements with return. If you really want to return item, then you can either use that instead of return, or use break.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.