Skip to content

Instantly share code, notes, and snippets.

@0livare
Created May 20, 2019 12:56
Show Gist options
  • Save 0livare/1562822aa650e31367c803a53721803b to your computer and use it in GitHub Desktop.
Save 0livare/1562822aa650e31367c803a53721803b to your computer and use it in GitHub Desktop.
class Node {
constructor(value) {
this.value = value
}
}
class Tree {
add(node) {
if (!this.root) {
this.root = node
return
}
let current = this.root
while(current) {
if (node.value > current.value) {
if (current.right) {
current = current.right
} else {
current.right = node
node.parent = current.right
return
}
} else {
if (current.left) {
current = current.left
} else {
current.left = node
node.parent = current.left
return
}
}
}
}
addAllValues(arr) {
for(let num of arr) {
this.add(new Node(num))
}
}
dfs(val, root = this.root) {
if (root.value === val) return root
if (root.left) {
let foundLeft = this.dfs(val, root.left)
if (foundLeft) return foundLeft
}
if (root.right) {
let foundRight = this.dfs(val, root.right)
if (foundRight) return foundRight
}
}
bfs(val) {
if (val === this.root.value) return this.root
return this._bfs(val, this.root)
}
// Separate function is necessary to avoid checking
// the parent's value twice
_bfs(val, root) {
if (root.left && root.left.value === val) return root.left
if (root.right && root.right.value === val) return root.right
if (root.left) {
let foundLeft = this._bfs(val, root.left)
if (foundLeft) return foundLeft
}
if (root.right) {
let foundRight = this._bfs(val, root.right)
if (foundRight) return foundRight
}
}
}
let tree = new Tree()
tree.addAllValues([5, 3, 7, 1, 2, 9, 8, 11])
console.log(tree.bfs(8))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment