Skip to content

Commit 63f346e

Browse files
committed
right rotate binary search tree
1 parent 53e6c19 commit 63f346e

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

Data Structures/Binary Tree/index.js

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ class BinaryTree {
176176
leftRotate(info) {
177177
let node = this.find(info) ? this.find(info).currentNode : null;
178178
let rightNode = node ? node.right : null;
179-
if (rightNode !== null) {
179+
if (rightNode) {
180180
// Copy the info
181181
let info = node.info;
182182
node.info = rightNode.info;
@@ -191,7 +191,23 @@ class BinaryTree {
191191
}
192192
}
193193

194-
rightRotate(info) {}
194+
rightRotate(info) {
195+
let node = this.find(info) ? this.find(info).currentNode : null;
196+
let leftNode = node ? node.left : null;
197+
if (leftNode !== null) {
198+
// Copy the info
199+
let info = node.info;
200+
node.info = leftNode.info;
201+
leftNode.info = info;
202+
203+
// right rotation
204+
node.left = leftNode.left;
205+
leftNode.left = leftNode.right;
206+
leftNode.right = node.right;
207+
node.right = leftNode;
208+
return this.rightRotate(leftNode.info);
209+
}
210+
}
195211
}
196212

197213
const bst1 = new BinaryTree();
@@ -201,8 +217,9 @@ bst1.add(5);
201217
bst1.add(11);
202218
bst1.add(-2);
203219
bst1.add(8);
204-
bst1.add(21);
220+
bst1.add(12);
221+
bst1.add(9);
205222
console.log(bst1.root);
206-
console.log(bst1.leftRotate(20));
223+
// console.log(bst1.leftRotate(20));
224+
console.log(bst1.rightRotate(20));
207225
console.log(bst1.root);
208-
console.log(bst1.find(21));

0 commit comments

Comments
 (0)