Add binary search tree.

This commit is contained in:
Oleksii Trekhleb 2018-04-03 07:37:19 +03:00
parent c5bccffe36
commit b89e406444
2 changed files with 50 additions and 1 deletions

View File

@ -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();
}
}

View File

@ -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();
});
});