Skip to content

Instantly share code, notes, and snippets.

@asm-jaime
Created May 4, 2018 14:50
Show Gist options
  • Save asm-jaime/1788160389c23b5bfef4bb51a0f19154 to your computer and use it in GitHub Desktop.
Save asm-jaime/1788160389c23b5bfef4bb51a0f19154 to your computer and use it in GitHub Desktop.
this javascript example about tree traversal with use recursion and simple cycle while
// ========== data
const data = [{
"value":49,
"childs":[
{"value":54, "childs":[
{"value":25, "childs":[{"value":5, "childs":[]},{"value":5, "childs":[]}]},
{"value":15, "childs":[{"value":25, "childs":[]},{"value":125, "childs":[]},{"value":625, "childs":[]},{"value":55, "childs":[]}]},
{"value":35, "childs":[{"value":25, "childs":[]}]}
]},
{"value":55, "childs":[{"value":85, "childs":[]},{"value":45, "childs":[]},{"value":25, "childs":[]}]},
{"value":75, "childs":[{"value":95, "childs":[]},{"value":65, "childs":[]}]}
]
}];
//const data = require('./data.json');
// ==========
// breadth-first search with use recursion
function recur_walker(tree, min) {
if(tree.value < min.value) {
min = tree;
}
if (tree.childs != null) {
for (let i = 0; i < tree.childs.length; ++i) {
min = recur_walker(tree.childs[i], min);
}
}
return min;
}
// breadth-first search with use while
function breadth_walker(tree) {
let history = [];
let current = {};
let min = tree[0];
while(tree.length > 0) {
current = tree.shift();
if(current.value < min.value) min = current;
if(current.childs != null) {
for(let i = 0; i < current.childs.length; ++i) {
tree.push(current.childs[i]);
}
}
}
return min;
}
function get_node(tree, history) {
let adress = 'tree[0]';
for(let i = 0; i < history.length; ++i){
adress = adress+'.childs['+history[i].toString()+']';
}
return eval(adress);
}
//depth first search with use while
function depth_walker(tree) {
const history = [0];
let current = tree[0];
let min = current;
while(history.length > 0) {
if(current === undefined){
history.pop();
history[history.length-1]++;
current = get_node(tree, history);
continue;
} else {
if(current.value < min.value) {
min = current;
}
}
if(current.childs.length > 0) {
history.push(0);
current = get_node(tree, history);
continue;
}
if(current.childs == null || current.childs.length < 1) {
history[history.length-1]++;
current = get_node(tree, history);
continue;
}
}
return min;
}
console.assert(
JSON.stringify(recur_walker(data[0], data[0])) ===
JSON.stringify(depth_walker(data)), 'results not the same'
)
// ==========
console.time('recur_walker');
console.log(recur_walker(data[0], data[0]));
console.timeEnd('recur_walker');
// ==========
console.time('depth_walker');
console.log(depth_walker(data));
console.timeEnd('depth_walker');
// ==========
console.time('breadth_walker');
console.log(breadth_walker(data));
console.timeEnd('breadth_walker');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment