mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-26 15:11:16 +08:00
Add binary search tree.
This commit is contained in:
parent
c5bccffe36
commit
b89e406444
@ -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();
|
||||
}
|
||||
}
|
||||
|
@ -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();
|
||||
});
|
||||
});
|
||||
|
Loading…
Reference in New Issue
Block a user