Skip to content

Instantly share code, notes, and snippets.

@gofer
Created August 6, 2024 02:15
Show Gist options
  • Save gofer/ab09594767ede2ae023247f27432b760 to your computer and use it in GitHub Desktop.
Save gofer/ab09594767ede2ae023247f27432b760 to your computer and use it in GitHub Desktop.
AVL Tree in JavaScript
class BinaryTreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
depth() {
let result = 0;
if (this.left) {
result = Math.max(result, this.left.depth() + 1);
}
if (this.right) {
result = Math.max(result, this.right.depth() + 1);
}
return result;
}
}
class AVLTreeNode extends BinaryTreeNode {
constructor(value) {
super(value);
}
rotateLeft() {
const B = this, A = B.right;
B.right = A.left;
A.left = B;
return A;
}
rotateRight() {
const A = this, B = A.left;
A.left = B.right;
B.right = A;
return B;
}
__insert(value) {
if (this.value == value) {
return 0;
}
if (value < this.value) {
if (this.left) {
this.left = this.left.__insert(value);
} else {
this.left = new AVLTreeNode(value);
}
const rightDepth = this.right ? this.right.depth() : 0;
console.log('L', this.value, this.left.depth(), rightDepth);
if (this.left.depth() - rightDepth > 0) {
return this.rotateRight();
} else {
return this;
}
} else { // value > this.value
if (this.right) {
this.right = this.right.__insert(value);
} else {
this.right = new AVLTreeNode(value);
}
const leftDepth = this.left ? this.left.depth() : 0;
console.log('R', this.value, this.right.depth(), leftDepth);
if (this.right.depth() - leftDepth > 0) {
return this.rotateLeft();
} else {
return this;
}
}
}
__show(depth = 0) {
let s = ' '.repeat(depth) + this.value + "\n";
if (this.left) {
s += this.left.__show(depth + 1);
}
if (this.right) {
s += this.right.__show(depth + 1);
}
return s;
}
}
class AVLTree {
constructor() {
this.root = null;
}
insert(value) {
if (!this.root) {
this.root = new AVLTreeNode(value);
return this;
}
this.root = this.root.__insert(value);
return this;
}
show() {
if (!this.root) {
return 'empty';
}
return this.root.__show();
}
}
const tree = new AVLTree();
for (let i = 1; i <= 100; ++i) {
tree.insert(i);
}
console.log(tree.show());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment