Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 83945de

Browse files
authoredOct 15, 2024··
Create AVLTree.js
1 parent ff314a2 commit 83945de

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
 

‎AVLTree.js

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
class Node {
2+
constructor(data) {
3+
this.data = data;
4+
this.left = null;
5+
this.right = null;
6+
this.height = 1;
7+
}
8+
}
9+
10+
class AVLTree {
11+
getHeight(node) {
12+
return node ? node.height : 0;
13+
}
14+
15+
getBalance(node) {
16+
return node ? this.getHeight(node.left) - this.getHeight(node.right) : 0;
17+
}
18+
19+
rightRotate(y) {
20+
let x = y.left;
21+
let T2 = x.right;
22+
x.right = y;
23+
y.left = T2;
24+
y.height = Math.max(this.getHeight(y.left), this.getHeight(y.right)) + 1;
25+
x.height = Math.max(this.getHeight(x.left), this.getHeight(x.right)) + 1;
26+
return x;
27+
}
28+
29+
leftRotate(x) {
30+
let y = x.right;
31+
let T2 = y.left;
32+
y.left = x;
33+
x.right = T2;
34+
x.height = Math.max(this.getHeight(x.left), this.getHeight(x.right)) + 1;
35+
y.height = Math.max(this.getHeight(y.left), this.getHeight(y.right)) + 1;
36+
return y;
37+
}
38+
39+
insert(node, data) {
40+
if (!node) return new Node(data);
41+
if (data < node.data) node.left = this.insert(node.left, data);
42+
else if (data > node.data) node.right = this.insert(node.right, data);
43+
else return node;
44+
45+
node.height = 1 + Math.max(this.getHeight(node.left), this.getHeight(node.right));
46+
let balance = this.getBalance(node);
47+
48+
if (balance > 1 && data < node.left.data) return this.rightRotate(node);
49+
if (balance < -1 && data > node.right.data) return this.leftRotate(node);
50+
if (balance > 1 && data > node.left.data) {
51+
node.left = this.leftRotate(node.left);
52+
return this.rightRotate(node);
53+
}
54+
if (balance < -1 && data < node.right.data) {
55+
node.right = this.rightRotate(node.right);
56+
return this.leftRotate(node);
57+
}
58+
return node;
59+
}
60+
61+
preOrder(node) {
62+
if (node !== null) {
63+
console.log(node.data);
64+
this.preOrder(node.left);
65+
this.preOrder(node.right);
66+
}
67+
}
68+
}
69+
70+
// Example usage
71+
let tree = new AVLTree();
72+
let root = null;
73+
root = tree.insert(root, 10);
74+
root = tree.insert(root, 20);
75+
root = tree.insert(root, 30);
76+
root = tree.insert(root, 40);
77+
root = tree.insert(root, 50);
78+
root = tree.insert(root, 25);
79+
console.log("Preorder traversal of the constructed AVL tree is:");
80+
tree.preOrder(root);

0 commit comments

Comments
 (0)
Please sign in to comment.