Created
February 8, 2021 01:35
-
-
Save clintonmedbery/c7f5a54af4b9299e9a77f5ff6d7f9b78 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(data){ | |
this.right = null; | |
this.left = null; | |
this.data = data | |
} | |
} | |
class Bst { | |
constructor() { | |
this.root = null; | |
} | |
insert(data) { | |
var node = new Node(data); | |
if (!this.root) { | |
this.root = node; | |
return this; | |
} | |
let current = this.root; | |
while (current) { | |
// duplicates check | |
if (data === current.data) { | |
return; | |
} | |
// left node insertion | |
if (data < current.data) { | |
if (!current.left) { | |
current.left = node; | |
break; | |
} | |
current = current.left; | |
} | |
//right node insertion | |
if (data > current.data) { | |
if (!current.right) { | |
current.right = node; | |
break; | |
} | |
current = current.right; | |
} | |
} | |
} | |
bfs(){ | |
let node = this.root; | |
const queue = [node]; | |
const finalData = [ ] | |
while(queue.length){ | |
//Pop off the first node | |
node = queue.shift() | |
if(node.left) queue.push(node.left) | |
if(node.right) queue.push(node.right) | |
finalData.push(node.data) | |
} | |
return finalData | |
} | |
dfs(){ | |
// final preorder list | |
const finalData = []; | |
function traverse(node){ | |
// push the data | |
finalData.push(node.data) | |
if(node.left) traverse(node.left) | |
if(node.right) traverse(node.right) | |
} | |
traverse(this.root); | |
return finalData; | |
} | |
} | |
let searchTree = new Bst() | |
searchTree.insert(8) | |
searchTree.insert(1) | |
searchTree.insert(9) | |
searchTree.insert(22) | |
searchTree.insert(3) | |
console.log(searchTree.bfs()) | |
console.log(searchTree.dfs()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment