Skip to content

Instantly share code, notes, and snippets.

@blasten
Last active August 29, 2015 14:14
Show Gist options
  • Save blasten/f15b002a96877e26b28e to your computer and use it in GitHub Desktop.
Save blasten/f15b002a96877e26b28e to your computer and use it in GitHub Desktop.
Depth and Breath first transversals without recursion in the DOM tree
function dfs(root, fn) {
if (!(root instanceof HTMLElement)) {
throw new Error('`root` should be an HTML Element');
return;
}
if (!(fn instanceof Function)) {
fn = function(element) {
console.debug(element);
}
}
// Each stack frame contains the parent node to transverse
var stack = [];
var current = root;
while (current !== null || stack.length !== 0) {
if (current === null) {
var top = stack[stack.length - 1];
if (top.nextElementSibling !== null) {
stack.pop();
stack.push(top.nextElementSibling);
current = top.nextElementSibling;
} else {
stack.pop();
}
// visit top
fn(top);
} else {
current = current.firstElementChild;
if (current !== null) {
stack.push(current);
}
}
}
// visit root
fn(root);
}
function bfs(root, fn) {
if (!(root instanceof HTMLElement)) {
throw new Error('`root` should be an HTML Element');
return;
}
if (!(fn instanceof Function)) {
fn = function(element) {
console.debug(element);
}
}
var queue = [root];
while (queue.length !== 0) {
var current = queue.shift();
// visit current
fn(current);
for (var i = 0; i < current.children.length; i++) {
queue.push(current.children[i]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment