Last active
April 12, 2019 03:22
-
-
Save ORESoftware/af4aed2317e36935ed016db4b7e22528 to your computer and use it in GitHub Desktop.
Simple breadth first traversal example
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
'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