mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-09-20 07:43:04 +08:00
Merge 60393e9404
into ca3d16dcce
This commit is contained in:
commit
6dc4bb9d5b
@ -64,7 +64,11 @@ export default class AvlTree extends BinarySearchTree {
|
|||||||
|
|
||||||
// Make left node to be a child of rootNode's parent.
|
// Make left node to be a child of rootNode's parent.
|
||||||
if (rootNode.parent) {
|
if (rootNode.parent) {
|
||||||
rootNode.parent.setLeft(leftNode);
|
if (rootNode.parent.left === rootNode) {
|
||||||
|
rootNode.parent.setLeft(leftNode);
|
||||||
|
} else {
|
||||||
|
rootNode.parent.setRight(leftNode);
|
||||||
|
}
|
||||||
} else if (rootNode === this.root) {
|
} else if (rootNode === this.root) {
|
||||||
// If root node is root then make left node to be a new root.
|
// If root node is root then make left node to be a new root.
|
||||||
this.root = leftNode;
|
this.root = leftNode;
|
||||||
@ -145,7 +149,11 @@ export default class AvlTree extends BinarySearchTree {
|
|||||||
|
|
||||||
// Make right node to be a child of rootNode's parent.
|
// Make right node to be a child of rootNode's parent.
|
||||||
if (rootNode.parent) {
|
if (rootNode.parent) {
|
||||||
rootNode.parent.setRight(rightNode);
|
if (rootNode.parent.left === rootNode) {
|
||||||
|
rootNode.parent.setLeft(rightNode);
|
||||||
|
} else {
|
||||||
|
rootNode.parent.setRight(rightNode);
|
||||||
|
}
|
||||||
} else if (rootNode === this.root) {
|
} else if (rootNode === this.root) {
|
||||||
// If root node is root then make right node to be a new root.
|
// If root node is root then make right node to be a new root.
|
||||||
this.root = rightNode;
|
this.root = rightNode;
|
||||||
|
@ -230,6 +230,23 @@ describe('AvlTree', () => {
|
|||||||
expect(tree.root.height).toBe(3);
|
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', () => {
|
it('should remove values from the tree with right-right rotation', () => {
|
||||||
const tree = new AvlTree();
|
const tree = new AvlTree();
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user