diff --git a/index.js b/index.js index 005de42..56d693a 100644 --- a/index.js +++ b/index.js @@ -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) => { @@ -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); @@ -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); diff --git a/index.spec.js b/index.spec.js index ace31d3..379cc27 100644 --- a/index.spec.js +++ b/index.spec.js @@ -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)', () => @@ -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); @@ -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()', () => { diff --git a/package.json b/package.json index bbc5305..b55b498 100644 --- a/package.json +++ b/package.json @@ -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": {