Created
January 20, 2016 20:18
-
-
Save blasten/ef75d3c374bfc6a1ef95 to your computer and use it in GitHub Desktop.
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
// Iterative depth first search | |
function IterativeDFSTraversal(root, fn, fnArgs) { | |
var stack = [], nodeIdx = [], stackFrameArgs = []; | |
fnArgs = fn(root, fnArgs); | |
if (fnArgs) { | |
stack.push(root); | |
nodeIdx.push(0); | |
stackFrameArgs.push(fnArgs); | |
} | |
while (stack.length > 0) { | |
var current = stack[stack.length - 1]; | |
var currentNodeIdx = nodeIdx[stack.length - 1]; | |
fnArgs = stackFrameArgs[stack.length - 1]; | |
if (currentNodeIdx >= current.children.length) { | |
stack.pop(); | |
nodeIdx.pop(); | |
} else { | |
fnArgs = fn(current.children[currentNodeIdx], fnArgs); | |
if (fnArgs) { | |
stack.push(current.children[currentNodeIdx]); | |
nodeIdx.push(0); | |
stackFrameArgs.push(fnArgs); | |
} | |
nodeIdx[stack.length - 1] = currentNodeIdx + 1; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment