Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [3.1.1] - 2020-04-01
### Fixed
- use the same balancing algorithm for insert and remove.

## [3.1.0] - 2020-03-31
### Added
- AvlTreeNode & AvlTree implementation.
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@datastructures-js/binary-search-tree",
"version": "3.1.0",
"version": "3.1.1",
"description": "binary search tree & avl tree (self balancing tree) implementation in javascript",
"main": "index.js",
"scripts": {
Expand Down
40 changes: 6 additions & 34 deletions src/avlTree.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,38 +14,10 @@ const AvlTreeNode = require('./avlTreeNode');
class AvlTree extends BinarySearchTree {
/**
* @private
* applies the proper rotation on nodes after inserting a node
* applies the proper rotation on nodes after an insert or remove
* @param {AvlTreeNode} node
*/
balanceAfterInsert(key, node) {
if (!node) return;

node.updateHeight();
const balance = node.calculateBalance();
if (balance > 1) {
if (key < node.getLeft().getKey()) {
node.rotateRight();
} else {
node.rotateLeftRight();
}
} else if (balance < -1) {
if (key > node.getRight().getKey()) {
node.rotateLeft();
} else {
node.rotateRightLeft();
}
}
if (node === this.rootNode && (balance < -1 || balance > 1)) {
this.rootNode = node.getParent();
}
}

/**
* @private
* applies the proper rotation on nodes after removing a node
* @param {AvlTreeNode} node
*/
balanceAfterRemove(node) {
balanceNode(node) {
if (!node) return;

node.updateHeight();
Expand Down Expand Up @@ -110,12 +82,12 @@ class AvlTree extends BinarySearchTree {

if (key < node.getKey()) {
const newNode = this.insert(key, value, node.getLeft());
this.balanceAfterInsert(key, node); // back-tracking
this.balanceNode(node); // back-tracking
return newNode;
}

const newNode = this.insert(key, value, node.getRight());
this.balanceAfterInsert(key, node); // back-tracking
this.balanceNode(node); // back-tracking
return newNode;
}

Expand All @@ -124,13 +96,13 @@ class AvlTree extends BinarySearchTree {

if (key < node.getKey()) {
const removed = this.remove(key, node.getLeft());
this.balanceAfterRemove(node);
this.balanceNode(node);
return removed;
}

if (key > node.getKey()) {
const removed = this.remove(key, node.getRight());
this.balanceAfterRemove(node);
this.balanceNode(node);
return removed;
}

Expand Down