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
9 changes: 6 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,6 @@ const binarySearchTree = () => {
/**
* inserts a node by a given value into the tree
* @param {(string|number)} value
* @param {object} node
*/
const insert = (value) => {
const insertFn = (currentNode) => {
Expand Down Expand Up @@ -192,7 +191,9 @@ const binarySearchTree = () => {
nodesCount -= 1;
} else if (right === null) {
// remove a node with a left child
if (currentNode.getValue() > parent.getValue()) {
if (parent === null) {
rootNode = left;
} else if (currentNode.getValue() > parent.getValue()) {
parent.setRight(left);
} else {
parent.setLeft(left);
Expand All @@ -201,7 +202,9 @@ const binarySearchTree = () => {
nodesCount -= 1;
} else if (left === null) {
// remove a node with a right child
if (currentNode.getValue() > parent.getValue()) {
if (parent === null) {
rootNode = right;
} else if (currentNode.getValue() > parent.getValue()) {
parent.setRight(right);
} else {
parent.setLeft(right);
Expand Down
27 changes: 25 additions & 2 deletions index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ describe('binarySearchTree tests', () => {
expect(bst.max().getValue(90))));

describe('.root()', () =>
it('should get the node with min value', () =>
it('should get the root node', () =>
expect(bst.root().getValue(50))));

describe('.find(value)', () =>
Expand Down Expand Up @@ -79,7 +79,6 @@ describe('binarySearchTree tests', () => {
expect(bst.count()).to.equal(5);
});


it('should remove a node with a left child only', () => {
bst.insert(30);
bst.remove(40);
Expand All @@ -96,6 +95,30 @@ describe('binarySearchTree tests', () => {
expect(bst.find(90).getLeft().getValue()).to.equal(60);
expect(bst.count()).to.equal(4);
});

it('should remove root node with right child', () => {
bst.insert(100);
bst.remove(60);
bst.remove(90);
bst.remove(30);
bst.remove(50);
expect(bst.root().getValue()).to.equal(100);
});

it('should remove root node with left child', () => {
bst.insert(20);
bst.insert(30);
bst.insert(25);
bst.remove(30);
bst.remove(25);
bst.remove(100);
expect(bst.root().getValue()).to.equal(20);
});

it('should remove root node', () => {
bst.remove(20);
expect(bst.root()).to.equal(null);
});
});

describe('.clear()', () => {
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": "1.0.2",
"version": "1.0.3",
"description": "binary search tree implementation in javascript",
"main": "index.js",
"scripts": {
Expand Down