class BinarySearchTree extends BinaryTree {
constructor (...args) {
super(...args);
}
find (key) {
if (!this.node) return this;
if (this.node.entry.key == key) return this;
if (this.node.entry.key < key) return this.node.right.find(key);
return this.node.left.find(key)
}
insert (entry) {
let t = this.find (entry.key);
if (t.node) throw `This key already in tree: ${entry.key}`;
t.node = new BinaryTreeNode (entry, new BinarySearchTree(),
new BinarySearchTree())
return t
}
leftmost () {
if (!this.node) throw "Tree has no nodes";
if (!this.node.left.node) return this;
return this.node.left.leftmost();
}
delete() {
if (!this.node) throw "Tree has no nodes";
if (!this.node.left.node) {
this.node = this.node.right.node
}
else if (!this.node.right.node) {
this.node = this.node.left.node
}
else {
let l = this.node.right.leftmost();
this.node.entry = l.node.entry;
l.delete()
}
}
clone() {
if (!this.node) return new BinarySearchTree();
return new BinarySearchTree (new BinaryTreeNode (this.node.entry,
this.node.left.clone(),
this.node.right.clone()))
}
}