diff --git a/src/data-structures/tree/binary-search-tree/BinarySearchTree.js b/src/data-structures/tree/binary-search-tree/BinarySearchTree.js index b7c06b4d..be440d70 100644 --- a/src/data-structures/tree/binary-search-tree/BinarySearchTree.js +++ b/src/data-structures/tree/binary-search-tree/BinarySearchTree.js @@ -13,7 +13,27 @@ export default class BinarySearchTree { return this.root.contains(value); } + remove(value) { + const nodeToRemove = this.findNode(value); + + if (!nodeToRemove) { + throw new Error('Item not found in the tree'); + } + + if (!nodeToRemove.left && !nodeToRemove.right) { + // Node is a leaf and thus has no children. + // Just remove the pointer to this node from the parent node. + } else if (nodeToRemove.left && nodeToRemove.right) { + // Node has two children. + // Find the next biggest value (minimum value in the right branch) + // and replace current value node with that next biggest value. + } else { + // Node has only one child. + // Make this child to be a direct child of current node's parent. + } + } + toString() { - this.root.toString(); + return this.root.toString(); } } diff --git a/src/data-structures/tree/binary-search-tree/__test__/BinarySearchTree.test.js b/src/data-structures/tree/binary-search-tree/__test__/BinarySearchTree.test.js index ae823edd..55a0c474 100644 --- a/src/data-structures/tree/binary-search-tree/__test__/BinarySearchTree.test.js +++ b/src/data-structures/tree/binary-search-tree/__test__/BinarySearchTree.test.js @@ -1,5 +1,34 @@ +import BinarySearchTree from '../BinarySearchTree'; + describe('BinarySearchTree', () => { it('should create binary search tree', () => { + const bst = new BinarySearchTree(); + expect(bst).toBeDefined(); + expect(bst.root).toBeDefined(); + expect(bst.root.value).toBeNull(); + expect(bst.root.left).toBeNull(); + expect(bst.root.right).toBeNull(); + }); + + it('should insert values', () => { + const bst = new BinarySearchTree(); + + bst.insert(10); + bst.insert(20); + bst.insert(5); + + expect(bst.toString()).toBe('5,10,20'); + }); + + it('should check if value exists', () => { + const bst = new BinarySearchTree(); + + bst.insert(10); + bst.insert(20); + bst.insert(5); + + expect(bst.contains(20)).toBeTruthy(); + expect(bst.contains(40)).toBeFalsy(); }); });