Last active
September 21, 2020 10:50
-
-
Save nirajrajgor/093d4799493edd1c7ac28546e51b0aa2 to your computer and use it in GitHub Desktop.
Breadth First Search in Javascript
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(data) { | |
this.data = data; | |
this.children = []; | |
} | |
add(data) { | |
this.children.push(new Node(data)); | |
} | |
remove(data) { | |
this.children = this.children.filter((child) => child.data !== data); | |
} | |
}; | |
class Tree { | |
constructor() { | |
this.root = null; | |
} | |
traverseBF(fn) { | |
if(!this.root){ | |
return false; | |
} | |
let arr = [this.root]; | |
while (arr.length) { | |
const node = arr.shift(); | |
fn(node); | |
arr.push(...node.children); | |
} | |
} | |
} | |
const letters = []; | |
const t = new Tree(); | |
t.root = new Node(20); | |
t.root.add(15); | |
t.root.add(30); | |
t.root.children[0].add(10); | |
t.root.children[0].add(18); | |
t.root.children[1].add(40); | |
t.traverseBF(node => { | |
letters.push(node.data); | |
}); | |
console.log(letters); // This will print [20, 15, 30, 10, 18, 40] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment