Skip to content

Instantly share code, notes, and snippets.

@sghall
Created January 18, 2017 08:39
Show Gist options
  • Save sghall/dc6884adf1e1ffce769a1349008a3ea7 to your computer and use it in GitHub Desktop.
Save sghall/dc6884adf1e1ffce769a1349008a3ea7 to your computer and use it in GitHub Desktop.
Breadth First Traversal and Depth First Traversal in JavaScript
//DFS
Tree.prototype.traverse = function (callback) {
var stack=[this];
var n;
while(stack.length>0) {
n = stack.pop();
callback(n.value);
if (!n.children) {
continue;
}
for (var i = n.children.length-1; i>=0; i--) {
stack.push(n.children[i]);
}
}
};
//BFS
Tree.prototype.traverse = function (callback) {
var queue=[this];
var n;
while(queue.length>0) {
n = queue.shift();
callback(n.value);
if (!n.children) {
continue;
}
for (var i = 0; i< n.children.length; i++) {
queue.push(n.children[i]);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment