Created
November 6, 2022 03:14
-
-
Save SparrowMike/e0896808a761f7ad046b23e606e8edab to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node { | |
constructor(value) { | |
this.value = value; | |
this.left = null; | |
this.right = null; | |
this.count = 0; | |
} | |
} | |
class BinarySearchTree { | |
constructor() { | |
this.root = null; | |
} | |
insert(value) { | |
let newNode = new Node(value); | |
if (!this.root) { | |
this.root = newNode; | |
return this; | |
} | |
let current = this.root | |
while(true) { | |
if (value === current.value) { | |
current.count ++; | |
return this; | |
} | |
if (value >= current.value) { | |
if (!current.right) { | |
current.right = newNode; | |
return this | |
} else { | |
current = current.right | |
} | |
} else { | |
if (!current.left) { | |
current.left = newNode; | |
return this | |
} else { | |
current = current.left | |
} | |
} | |
} | |
} | |
find(value) { | |
if (!this.root) { | |
return false; | |
} | |
let current = this.root, | |
found = false; | |
while(current && !found) { | |
if (value > current.value) { | |
current = current.right | |
} else if (value < current.value){ | |
current = current.left | |
} else { | |
found = true | |
} | |
} | |
if (!current) return false; | |
return current | |
} | |
BFS() { | |
let node = this.root, | |
queue = [], | |
data = []; | |
queue.push(node) | |
while(queue.length) { | |
node = queue.shift() | |
data.push(node.value) | |
if(node.left) queue.push(node.left) | |
if(node.right) queue.push(node.right) | |
} | |
return data | |
} | |
DFSPreOrder() { | |
let data = []; | |
traverse(this.root) | |
function traverse(node) { | |
data.push(node.value); | |
if (node.left) traverse(node.left); | |
if (node.right) traverse(node.right); | |
} | |
return data; | |
} | |
DFSPostOrder() { | |
let data = []; | |
traverse(this.root) | |
function traverse(node) { | |
if (node.left) traverse(node.left); | |
if (node.right) traverse(node.right); | |
data.push(node.value); | |
} | |
return data; | |
} | |
DFSInOrder() { | |
let data = []; | |
traverse(this.root) | |
function traverse(node) { | |
if (node.left) traverse(node.left); | |
data.push(node.value); | |
if (node.right) traverse(node.right); | |
} | |
return data; | |
} | |
} | |
let bst = new BinarySearchTree |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
❤️🔥