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;
}
addLeft(node) {
setLeft(node) {
this.left = node;
return this;
}
addRight(node) {
setRight(node) {
this.right = node;
return this;
}

View File

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

View File

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

View File

@ -9,6 +9,15 @@ describe('BinarySearchTreeNode', () => {
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', () => {
const bstNode = new BinarySearchTreeNode(2);
bstNode.insert(1);