Created
June 15, 2020 15:31
-
-
Save andresabello/92b608f1ba3c39de3d921504a3185323 to your computer and use it in GitHub Desktop.
Binary Search Tree
This file contains hidden or 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.left = null | |
this.right = null | |
this.value = value | |
} | |
} | |
class BinarySearchTree { | |
constructor() { | |
this.root = null | |
} | |
insert(value) { | |
let node = new Node(value) | |
//is value the first then root | |
if (this.root === null) { | |
this.root = node | |
return this | |
} | |
let currentNode = this.root | |
while (true) { | |
if (value < currentNode.value) { | |
if (!currentNode.left) { | |
currentNode.left = node | |
return this | |
} | |
currentNode = currentNode.left | |
}else { | |
if (!currentNode.right) { | |
currentNode.right = node | |
return this | |
} | |
currentNode = currentNode.right | |
} | |
} | |
} | |
lookup(value) { | |
} | |
remove(value) { | |
} | |
bfs() { | |
let currentNode = this.root | |
let list = [] | |
let queue = [] | |
queue.push(currentNode) | |
while(queue.length > 0) { | |
currentNode = queue.shift() | |
if (currentNode.left) { | |
queue.push(currentNode.left) | |
} | |
if (currentNode.right) { | |
queue.push(currentNode.right) | |
} | |
} | |
return list | |
} | |
} | |
const tree = new BinarySearchTree() | |
tree.insert(9) | |
tree.insert(4) | |
tree.insert(6) | |
tree.insert(20) | |
tree.insert(170) | |
tree.insert(15) | |
tree.insert(1) | |
tree.insert(300) | |
tree.insert(99) | |
tree.insert(78) | |
// tree.bfs() | |
let log = JSON.stringify(traverse(tree.root)) | |
console.log(log) | |
function traverse(node) { | |
if (node && node.value) { | |
const tree = {value: node.value} | |
tree.left = node.leff === null ? null : traverse(node.left) | |
tree.right = node.right === null ? null : traverse(node.right) | |
return tree | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment