Binary Search Tree
Binary Search Tree is a tree type data structure. It start with one root node and the node can only contain two children, and we can call left hand side and right head side. In the Binary Search Tree needs follows one rule, the left hand side must be smaller than the its parent and its ancestor which if child is on its left hand side , and the right hand side should be greater than its parent and its ancestor.
Implementation
class Node {
constructor(value) {
this.value = value
this.left = null
this.right = null
}
}
class BinarySearchTree {
constructor() {
this.root = null
}
add(value) {
if (!this.root) {
this.root = new Node(value)
return this
}
let current = this.root
while (true) {
if (current.value > value) {
if (current.right) {
current = current.rigth
} else {
current.right = new Node(value)
break
}
} else {
if (current.left) {
current = current.left
} else {
current.left = new Node(value)
break
}
}
}
return this
}
}