Created
December 17, 2013 04:10
-
-
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.
This file contains hidden or 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
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