Binary Search Tree Experiments
by AntowaKartowa
HTML
<script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
<script>
mermaid.initialize({ startOnLoad: true });
</script>
<div id="container"></div>
JavaScript
class BiLinkedList {
#head = null;
#tail = null;
size = 0;
constructor(...items) {
if (items.length) {
[...items].forEach(item => this.push(item))
}
}
#createNode(val, prev = null, next = null) {
return { val, next, prev }
}
push(val) {
const newNode = this.#createNode(val, this.#tail);
if (this.#head === null) {
this.#head = newNode;
this.#tail = newNode;
} else {
this.#tail.next = newNode;
this.#tail = newNode;
}
this.size++;
return this;
}
pop() {
if (this.#tail === null) return;
const removedNode = this.#tail;
this.#tail = removedNode.prev;
removedNode.prev = null;
if (this.#tail) this.#tail.next = null;
else this.#head = null;
this.size--;
return removedNode;
}
unshift(val) {
const newNode = this.#createNode(val, null, this.#head);
if (this.#head === null) {
this.#head = newNode;
this.#tail = newNode;
} else {
this.#head.prev = newNode;
this.#head = newNode;
}
this.size++;
return this;
}
shift() {
if (this.#head === null) return;
const removedNode = this.#head;
this.#head = removedNode.next;
removedNode.next = null;
if (this.#head) this.#head.prev = null;
else this.#tail = null;
this.size--;
return removedNode;
}
insert(index = 0, val) {
if (index < 0 || index > this.size) return false;
if (index === 0) return this.unshift(val);
if (index === this.size) return this.push(val);
const newNode = this.#createNode(val);
const after = this.get(index);
const before = after.prev;
before.next = newNode;
after.prev = newNode;
newNode.prev = before;
newNode.next = after;
this.size++;
return this;
}
get(index = 0) {
if (index < 0 || index >= this.size) return null;
if (index === 0) return this.#head;
if (index === this.size - 1) return...