Skip to content

Instantly share code, notes, and snippets.

@ORESoftware
Last active April 12, 2019 03:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ORESoftware/af4aed2317e36935ed016db4b7e22528 to your computer and use it in GitHub Desktop.
Save ORESoftware/af4aed2317e36935ed016db4b7e22528 to your computer and use it in GitHub Desktop.
Simple breadth first traversal example
'use strict';
const queue = [];
const root = {};
const main = {
name: 'main',
linkedSet:{
a: {
name: 'a',
linkedSet: {}
},
b: {
name: 'b',
linkedSet: {
c: {
name: 'c',
linkedSet: {}
},
d: {
name: 'd',
linkedSet: {
e: {
name: 'e',
linkedSet: {
i: {
name: 'i',
linkedSet: {}
}
}
}
}
},
f: {
name: 'f',
linkedSet: {
g: {
name: 'g',
linkedSet: {
h: {
name: 'h',
linkedSet: {}
}
}
}
}
}
}
}
}
};
let counter = 0;
const addBreadthFirst = (currTreeNode, dep) => {
for (let v of Object.values(dep.linkedSet)) {
if (v.visited) {
continue;
}
v.visited = true;
queue.push([currTreeNode[v.name] = {count: counter++}, v]);
}
const next = queue.shift();
if(next){
addBreadthFirst(...next);
}
};
addBreadthFirst(root, main);
console.log(JSON.stringify(root));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment