JSFiddle - React, Tailwind, and code Playground
by Fareez Ahmed
JavaScript
function BinarySearchTree(value) {
this.val = value;
this.left = null;
this.right = null;
}
//insert
BinarySearchTree.prototype.insert = function (toInsert) {
if (this.val > toInsert) {
if (this.left === null) {
this.left = new BinarySearchTree(toInsert);
} else {
this.left.insert(toInsert);
}
}
if (this.val < toInsert) {
if (this.right === null) {
this.right = new BinarySearchTree(toInsert);
} else {
this.right.insert(toInsert);
}
}
};
//contains
BinarySearchTree.prototype.contains = function (target) {
if (this.val === target) {
return true;
}
if (this.left && this.val > target) {
return this.left.contains(target);
}
if (this.right && this.val < target) {
return this.right.contains(target);
}
return false;
};
//depth first log
BinarySearchTree.prototype.depthFirstLog = function (callback) {
this.val = callback(this.val);
if (this.left) {
this.left.depthFirstLog(callback);
}
if (this.right) {
this.right.depthFirstLog(callback);
}
};
var bst = new BinarySearchTree(7);
bst.insert(9);
bst.insert(6);
bst.insert(4);
console.log(bst);
console.log(bst.contains(9));
console.log(bst.contains(6));
console.log(bst.contains(4));
console.log(bst.contains(5));
console.log(bst.contains(7));
bst.depthFirstLog(function (val) {
console.log(val);
return val * 2;
});
console.log(bst);