Add binary search tree.

This commit is contained in:
Oleksii Trekhleb
2018-04-02 17:50:56 +03:00
parent 00e40a0eca
commit d6be33842c
8 changed files with 184 additions and 1 deletions

View File

@@ -0,0 +1,19 @@
import BinarySearchTreeNode from './BinarySearchTreeNode';
export default class BinarySearchTree {
constructor() {
this.root = new BinarySearchTreeNode();
}
insert(value) {
this.root.insert(value);
}
contains(value) {
return this.root.contains(value);
}
toString() {
this.root.toString();
}
}

View File

@@ -0,0 +1,38 @@
import BinaryTreeNode from '../BinaryTreeNode';
export default class BinarySearchTreeNode extends BinaryTreeNode {
insert(value) {
if (value < this.value) {
// Insert to the left.
if (this.left) {
this.left.insert(value);
} else {
this.left = new BinarySearchTreeNode(value);
}
} else {
// Insert to the right.
if (this.right) {
this.right.insert(value);
} else {
this.right = new BinarySearchTreeNode(value);
}
}
return this;
}
contains(value) {
// Check the root.
if (this.value === value) {
return true;
}
if (value < this.value && this.left) {
return this.left.contains(value);
} else if (this.right) {
return this.right.contains(value);
}
return false;
}
}

View File

@@ -0,0 +1,5 @@
describe('BinarySearchTree', () => {
it('should create binary search tree', () => {
});
});

View File

@@ -0,0 +1,44 @@
import BinarySearchTreeNode from '../BinarySearchTreeNode';
describe('BinarySearchTreeNode', () => {
it('should create binary search tree', () => {
const bstNode = new BinarySearchTreeNode(2);
expect(bstNode.value).toBe(2);
expect(bstNode.left).toBeNull();
expect(bstNode.right).toBeNull();
});
it('should insert nodes in correct order', () => {
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(3);
expect(bstNode.toString()).toBe('1,2,3');
expect(bstNode.contains(3)).toBeTruthy();
expect(bstNode.contains(4)).toBeFalsy();
bstNode.insert(7);
expect(bstNode.toString()).toBe('1,2,3,7');
expect(bstNode.contains(7)).toBeTruthy();
expect(bstNode.contains(8)).toBeFalsy();
bstNode.insert(4);
expect(bstNode.toString()).toBe('1,2,3,4,7');
expect(bstNode.contains(4)).toBeTruthy();
expect(bstNode.contains(8)).toBeFalsy();
bstNode.insert(6);
expect(bstNode.toString()).toBe('1,2,3,4,6,7');
expect(bstNode.contains(6)).toBeTruthy();
expect(bstNode.contains(8)).toBeFalsy();
});
});