Created
January 18, 2017 08:39
-
-
Save sghall/dc6884adf1e1ffce769a1349008a3ea7 to your computer and use it in GitHub Desktop.
Breadth First Traversal and Depth First Traversal in JavaScript
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
//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