Skip to content

Instantly share code, notes, and snippets.

@jimkang
Created December 17, 2013 04:10
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimkang/7999909 to your computer and use it in GitHub Desktop.
Save jimkang/7999909 to your computer and use it in GitHub Desktop.
A function to flatten a tree, depth-first. It's an implementation of this algorithm: http://cl.ly/image/1X1i0b1v1H2d Assumes the tree is built via nodes that have a property named 'children' which is an array of other nodes.
function flattenTreeDepthFirst(rootNode) {
var nodes = [rootNode];
var childArraysQueue = [];
if (rootNode.children) {
childArraysQueue.push(rootNode.children);
}
while (childArraysQueue.length > 0) {
var children = childArraysQueue[0];
if (children.length > 0) {
var child = children.shift();
if (children.length < 1) {
childArraysQueue.shift();
}
if (child.children && child.children.length > 0) {
childArraysQueue.unshift(child.children);
}
nodes.push(child);
}
}
return nodes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment