Skip to content

Instantly share code, notes, and snippets.

@nirajrajgor
Last active September 21, 2020 11:20
Show Gist options
  • Save nirajrajgor/13bc294e61ee05e10bb640ba8e25f947 to your computer and use it in GitHub Desktop.
Save nirajrajgor/13bc294e61ee05e10bb640ba8e25f947 to your computer and use it in GitHub Desktop.
Depth First Search with Pre Order 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;
}
// DFS with Pre Order traversal
traverseDF(fn) {
if(!this.root){
return;
}
let arr = [this.root];
while (arr.length) {
const node = arr.shift();
fn(node);
arr.unshift(...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.traverseDF(node => {
letters.push(node.data);
});
console.log(letters); // This will print [20, 15, 10, 18, 30, 40]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment