Add binary search tree.

This commit is contained in:
Oleksii Trekhleb 2018-04-03 07:35:13 +03:00
parent ff2df770b8
commit c5bccffe36
4 changed files with 20 additions and 6 deletions

View File

@ -5,12 +5,12 @@ export default class BinaryTreeNode {
this.value = value; this.value = value;
} }
addLeft(node) { setLeft(node) {
this.left = node; this.left = node;
return this; return this;
} }
addRight(node) { setRight(node) {
this.right = node; this.right = node;
return this; return this;
} }

View File

@ -15,8 +15,8 @@ describe('BinaryTreeNode', () => {
const rootNode = new BinaryTreeNode(2); const rootNode = new BinaryTreeNode(2);
rootNode rootNode
.addLeft(leftNode) .setLeft(leftNode)
.addRight(rightNode); .setRight(rightNode);
expect(rootNode.value).toBe(2); expect(rootNode.value).toBe(2);
expect(rootNode.left.value).toBe(1); expect(rootNode.left.value).toBe(1);
@ -29,8 +29,8 @@ describe('BinaryTreeNode', () => {
const rootNode = new BinaryTreeNode(2); const rootNode = new BinaryTreeNode(2);
rootNode rootNode
.addLeft(leftNode) .setLeft(leftNode)
.addRight(rightNode); .setRight(rightNode);
expect(rootNode.traverseInOrder()).toEqual([1, 2, 3]); expect(rootNode.traverseInOrder()).toEqual([1, 2, 3]);

View File

@ -2,6 +2,11 @@ import BinaryTreeNode from '../BinaryTreeNode';
export default class BinarySearchTreeNode extends BinaryTreeNode { export default class BinarySearchTreeNode extends BinaryTreeNode {
insert(value) { insert(value) {
if (this.value === null) {
this.value = value;
return this;
}
if (value < this.value) { if (value < this.value) {
// Insert to the left. // Insert to the left.
if (this.left) { if (this.left) {

View File

@ -9,6 +9,15 @@ describe('BinarySearchTreeNode', () => {
expect(bstNode.right).toBeNull(); expect(bstNode.right).toBeNull();
}); });
it('should insert in itself if it is empty', () => {
const bstNode = new BinarySearchTreeNode();
bstNode.insert(1);
expect(bstNode.value).toBe(1);
expect(bstNode.left).toBeNull();
expect(bstNode.right).toBeNull();
});
it('should insert nodes in correct order', () => { it('should insert nodes in correct order', () => {
const bstNode = new BinarySearchTreeNode(2); const bstNode = new BinarySearchTreeNode(2);
bstNode.insert(1); bstNode.insert(1);