Simple BinarySearchTree
by Dan Mathisen
HTML
<p class="res1"></p>
<p class="res2"></p>
JavaScript
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
insert(value) {
let newNode = new Node(value);
if (!this.root) {
this.root = newNode;
return this;
}
let current = this.root;
while(current) {
if (value === current.value) return -1;
if (value < current.value) {
if (!current.left) {
current.left = newNode;
break;
}
current = current.left
} else {
if (!current.right) {
current.right = newNode;
break;
}
current = current.right;
}
}
return this;
}
find(value) {
if (!this.root) return undefined;
let current = this.root;
while(current) {
if (value === current.value) return true;
if (value < current.value) {
current = current.left;
} else {
current = current.right;
}
}
return false;
}
}
const tree = new BinarySearchTree();
tree.insert(10);
tree.insert(6);
tree.insert(3);
tree.insert(8);
tree.insert(15);
tree.insert(20);
const result1 = tree.find(8);
const result2 = tree.find(22);
document.querySelector('.res1').textContent = result1;
document.querySelector('.res2').textContent = result2;