JSFiddle - React, Tailwind, and code Playground
JavaScript
var binaryTreeNode = function (value) {
this.value = value;
};
var binarySearchTree = function () {
var tree = Object.create(binarySearchTreeMethods);
tree.root = null;
return tree;
};
var binarySearchTreeMethods = {
insert: function (value, node) {
var newNode = new binaryTreeNode(value);
// check if tree is empty
if (this.isEmpty()) {
this.root = newNode;
return;
}
// initialize node
if (node === void 0) node = this.root;
// compare value with node.value
if (value <= node.value) {
// check if left exists
if (node.left) {
this.insert(value, node.left);
} else {
node.left = newNode;
}
} else {
if (node.right) {
this.insert(value, node.right);
} else {
node.right = newNode;
}
}
},
contains: function (value, node) {
if (this.isEmpty()) return false;
// tree is not empty - initialize node
if (node === void 0) node = this.root;
// check if node's value is the value
if (value === node.value) return true;
if (value < node.value) {
// check if left node exists
return node.left ? this.contains(value, node.left) : false;
} else {
// check if right node exists
return node.right ? this.contains(value, node.right) : false;
}
},
findMaxValue: function (node) {
if (!this.isEmpty()) {
if (node === void 0) node = this.root;
while (node.right) {
node = node.right;
}
return node.value;
}
},
remove: function (value) {
this.root = this.root && this.root.remove(value);
},
values: function () {
function valuesInner(node) {
return node ?...