This commit is contained in:
$SH 2024-07-17 10:37:49 +09:00 committed by GitHub
commit 6dc4bb9d5b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 27 additions and 2 deletions

View File

@ -64,7 +64,11 @@ export default class AvlTree extends BinarySearchTree {
// Make left node to be a child of rootNode's parent.
if (rootNode.parent) {
if (rootNode.parent.left === rootNode) {
rootNode.parent.setLeft(leftNode);
} else {
rootNode.parent.setRight(leftNode);
}
} else if (rootNode === this.root) {
// If root node is root then make left node to be a new root.
this.root = leftNode;
@ -145,7 +149,11 @@ export default class AvlTree extends BinarySearchTree {
// Make right node to be a child of rootNode's parent.
if (rootNode.parent) {
if (rootNode.parent.left === rootNode) {
rootNode.parent.setLeft(rightNode);
} else {
rootNode.parent.setRight(rightNode);
}
} else if (rootNode === this.root) {
// If root node is root then make right node to be a new root.
this.root = rightNode;

View File

@ -230,6 +230,23 @@ describe('AvlTree', () => {
expect(tree.root.height).toBe(3);
});
it('should do right right rotation and keeping left node safe', () => {
const tree = new AvlTree();
tree.insert(24);
tree.insert(12);
tree.insert(34);
tree.insert(15);
expect(tree.toString()).toBe('12,15,24,34');
tree.insert(18);
expect(tree.toString()).toBe('12,15,18,24,34');
expect(tree.root.height).toBe(2);
expect(tree.root.left.value).toBe(15);
expect(tree.root.left.left.value).toBe(12);
expect(tree.root.left.right.value).toBe(18);
});
it('should remove values from the tree with right-right rotation', () => {
const tree = new AvlTree();