Skip to content

Instantly share code, notes, and snippets.

@nirajrajgor
Created September 21, 2020 11:33
Show Gist options
  • Save nirajrajgor/607898d5d2503f949b4e11593e909335 to your computer and use it in GitHub Desktop.
Save nirajrajgor/607898d5d2503f949b4e11593e909335 to your computer and use it in GitHub Desktop.
Depth First Search with Post Order Traversal 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 Post Order traversal
traverseDFPost(fn) {
let arr = [this.root];
let result = [];
while (arr.length) {
const node = arr.pop();
result.unshift(node);
arr.push(...node.children);
}
while (result.length) {
const node = result.shift();
fn(node);
}
}
}
const lettersPostOrder = [];
const t1 = new Tree();
t1.root = new Node(20);
t1.root.add(15);
t1.root.add(30);
t1.root.children[0].add(10);
t1.root.children[0].add(18);
t1.root.children[1].add(40);
t1.traverseDFPost(node => {
lettersPostOrder.push(node.data);
});
console.log(lettersPostOrder); // This will print [10, 18, 15, 40, 30, 20]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment