\$\begingroup\$
\$\endgroup\$
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);
};
asked Oct 16, 2015 at 20:09
1 Answer 1
\$\begingroup\$
\$\endgroup\$
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
.
answered Oct 16, 2015 at 20:57
default