Skip to content

Commit 60393e9

Browse files
committed
Fix Bug in AVL Tree rorateLeftLeft and rotateRightRight
1 parent 2267642 commit 60393e9

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

src/data-structures/tree/avl-tree/AvlTree.js

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,11 @@ export default class AvlTree extends BinarySearchTree {
6464

6565
// Make left node to be a child of rootNode's parent.
6666
if (rootNode.parent) {
67-
rootNode.parent.setLeft(leftNode);
67+
if (rootNode.parent.left === rootNode) {
68+
rootNode.parent.setLeft(leftNode);
69+
} else {
70+
rootNode.parent.setRight(leftNode);
71+
}
6872
} else if (rootNode === this.root) {
6973
// If root node is root then make left node to be a new root.
7074
this.root = leftNode;
@@ -145,7 +149,11 @@ export default class AvlTree extends BinarySearchTree {
145149

146150
// Make right node to be a child of rootNode's parent.
147151
if (rootNode.parent) {
148-
rootNode.parent.setRight(rightNode);
152+
if (rootNode.parent.left === rootNode) {
153+
rootNode.parent.setLeft(rightNode);
154+
} else {
155+
rootNode.parent.setRight(rightNode);
156+
}
149157
} else if (rootNode === this.root) {
150158
// If root node is root then make right node to be a new root.
151159
this.root = rightNode;

src/data-structures/tree/avl-tree/__test__/AvlTRee.test.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,23 @@ describe('AvlTree', () => {
230230
expect(tree.root.height).toBe(3);
231231
});
232232

233+
it('should do right right rotation and keeping left node safe', () => {
234+
const tree = new AvlTree();
235+
tree.insert(24);
236+
tree.insert(12);
237+
tree.insert(34);
238+
tree.insert(15);
239+
240+
expect(tree.toString()).toBe('12,15,24,34');
241+
242+
tree.insert(18);
243+
expect(tree.toString()).toBe('12,15,18,24,34');
244+
expect(tree.root.height).toBe(2);
245+
expect(tree.root.left.value).toBe(15);
246+
expect(tree.root.left.left.value).toBe(12);
247+
expect(tree.root.left.right.value).toBe(18);
248+
});
249+
233250
it('should remove values from the tree with right-right rotation', () => {
234251
const tree = new AvlTree();
235252

0 commit comments

Comments
 (0)