Skip to content

Instantly share code, notes, and snippets.

@nirajrajgor
Last active September 21, 2020 10:50
Show Gist options
  • Save nirajrajgor/093d4799493edd1c7ac28546e51b0aa2 to your computer and use it in GitHub Desktop.
Save nirajrajgor/093d4799493edd1c7ac28546e51b0aa2 to your computer and use it in GitHub Desktop.
Breadth First Search in Javascript
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