Skip to content

Instantly share code, notes, and snippets.

@UniBreakfast
Created December 16, 2024 10:23
Show Gist options
  • Select an option

  • Save UniBreakfast/1ec08b4873eec3b2532105424c3fd2f5 to your computer and use it in GitHub Desktop.

Select an option

Save UniBreakfast/1ec08b4873eec3b2532105424c3fd2f5 to your computer and use it in GitHub Desktop.
Binary Search Tree rough implementation in console
bst = Object.create({
empty() {
this.value = null
this.left = null
this.right = null
},
show() {
let output = `${this.value}`
if (this.left && this.right) {
output = ` ${output}\n / \\\n${this.left.value} ${this.right.value}`
} else if (this.left) {
output = ` ${output}\n /\n${this.left.value}`
} else if (this.right) {
output = `${output}\n \\\n ${this.right.value}`
}
console.log(output)
if (this.left?.left?.value || this.left?.right?.value) this.left.show()
if (this.right?.left?.value || this.right?.right?.value) this.right.show()
},
add(value) {
if (this.value === undefined || this.value === null) {
this.value = value
} else {
if (value < this.value) {
if (!this.left || this.left.value === undefined || this.left === null) {
this.left = Object.assign(Object.create(Object.getPrototypeOf(this)), {value})
} else {
this.add.call(this.left, value)
}
} else if (value > this.value) {
if (!this.right || this.right.value === undefined || this.right === null) {
this.right = Object.assign(Object.create(Object.getPrototypeOf(this)), {value})
} else {
this.add.call(this.right, value)
}
}
}
this.show()
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment