mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-26 07:01:18 +08:00
Fix issue #37 with AVL tree.
This commit is contained in:
parent
924066bb0c
commit
90b56bc3d3
@ -80,6 +80,12 @@ export default class AvlTree extends BinarySearchTree {
|
||||
const leftRightNode = leftNode.right;
|
||||
leftNode.setRight(null);
|
||||
|
||||
// Preserve leftRightNode's left subtree.
|
||||
if (leftRightNode.left) {
|
||||
leftNode.setRight(leftRightNode.left);
|
||||
leftRightNode.setLeft(null);
|
||||
}
|
||||
|
||||
// Attach leftRightNode to the rootNode.
|
||||
rootNode.setLeft(leftRightNode);
|
||||
|
||||
@ -102,6 +108,11 @@ export default class AvlTree extends BinarySearchTree {
|
||||
const rightLeftNode = rightNode.left;
|
||||
rightNode.setLeft(null);
|
||||
|
||||
if (rightLeftNode.right) {
|
||||
rightNode.setLeft(rightLeftNode.right);
|
||||
rightLeftNode.setRight(null);
|
||||
}
|
||||
|
||||
// Attach rightLeftNode to the rootNode.
|
||||
rootNode.setRight(rightLeftNode);
|
||||
|
||||
|
@ -45,3 +45,4 @@ AVL tree with balance factors (green)
|
||||
* [Tutorials Point](https://www.tutorialspoint.com/data_structures_algorithms/avl_tree_algorithm.htm)
|
||||
* [BTech](http://btechsmartclass.com/DS/U5_T2.html)
|
||||
* [AVL Tree Insertion on YouTube](https://www.youtube.com/watch?v=rbg7Qf8GkQ4&list=PLLXdhg_r2hKA7DPDsunoDZ-Z769jWn4R8&index=12&)
|
||||
* [AVL Tree Operations Visualisations](https://www.cs.usfca.edu/~galles/visualization/AVLtree.html)
|
||||
|
@ -185,4 +185,48 @@ describe('AvlTree', () => {
|
||||
expect(tree.root.height).toBe(2);
|
||||
expect(tree.toString()).toBe('6,8,9,18,21,22,43');
|
||||
});
|
||||
|
||||
it('should do left right rotation and keeping left right node safe', () => {
|
||||
const tree = new AvlTree();
|
||||
|
||||
tree.insert(30);
|
||||
tree.insert(15);
|
||||
tree.insert(40);
|
||||
tree.insert(10);
|
||||
tree.insert(18);
|
||||
tree.insert(35);
|
||||
tree.insert(45);
|
||||
tree.insert(5);
|
||||
tree.insert(12);
|
||||
|
||||
expect(tree.toString()).toBe('5,10,12,15,18,30,35,40,45');
|
||||
expect(tree.root.height).toBe(3);
|
||||
|
||||
tree.insert(11);
|
||||
|
||||
expect(tree.toString()).toBe('5,10,11,12,15,18,30,35,40,45');
|
||||
expect(tree.root.height).toBe(3);
|
||||
});
|
||||
|
||||
it('should do left right rotation and keeping left right node safe', () => {
|
||||
const tree = new AvlTree();
|
||||
|
||||
tree.insert(30);
|
||||
tree.insert(15);
|
||||
tree.insert(40);
|
||||
tree.insert(10);
|
||||
tree.insert(18);
|
||||
tree.insert(35);
|
||||
tree.insert(45);
|
||||
tree.insert(42);
|
||||
tree.insert(47);
|
||||
|
||||
expect(tree.toString()).toBe('10,15,18,30,35,40,42,45,47');
|
||||
expect(tree.root.height).toBe(3);
|
||||
|
||||
tree.insert(43);
|
||||
|
||||
expect(tree.toString()).toBe('10,15,18,30,35,40,42,43,45,47');
|
||||
expect(tree.root.height).toBe(3);
|
||||
});
|
||||
});
|
||||
|
Loading…
Reference in New Issue
Block a user