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,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;
}
}