Add binary search tree.

This commit is contained in:
Oleksii Trekhleb 2018-04-03 06:41:45 +03:00
parent 8caf3a2201
commit 873024079a
2 changed files with 17 additions and 2 deletions

View File

@ -9,7 +9,7 @@ export default class BinarySearchTreeNode extends BinaryTreeNode {
} else {
this.left = new BinarySearchTreeNode(value);
}
} else {
} else if (value > this.value) {
// Insert to the right.
if (this.right) {
this.right.insert(value);
@ -30,7 +30,7 @@ export default class BinarySearchTreeNode extends BinaryTreeNode {
if (value < this.value && this.left) {
// Check left nodes.
return this.left.contains(value);
} else if (this.right) {
} else if (value > this.value && this.right) {
// Check right nodes.
return this.right.contains(value);
}

View File

@ -41,4 +41,19 @@ describe('BinarySearchTreeNode', () => {
expect(bstNode.contains(6)).toBeTruthy();
expect(bstNode.contains(8)).toBeFalsy();
});
it('should not insert duplicates', () => {
const bstNode = new BinarySearchTreeNode(2);
bstNode.insert(1);
expect(bstNode.toString()).toBe('1,2');
expect(bstNode.contains(1)).toBeTruthy();
expect(bstNode.contains(3)).toBeFalsy();
bstNode.insert(1);
expect(bstNode.toString()).toBe('1,2');
expect(bstNode.contains(1)).toBeTruthy();
expect(bstNode.contains(3)).toBeFalsy();
});
});