JSFiddle - React, Tailwind, and code Playground
codility - 3 - Depth first loop
by Csaba Hellinger
HTML
Do the same thing without recursion.
Check the console for the results.
JavaScript
const root = {
name: "root", children: [
{ name: "1", children: [
{ name: "11", children: [
{ name: "111" },
{ name: "112" }
]},
{ name: "12", children: [
{ name: "121" }
]}
]},
{ name: "2", children: [
{ name: "21", children: [
{ name: "211" },
{ name: "212" }
]},
{ name: "22" }
]}
]
};
///*
const getAllNames = (node, list = []) => {
list.push(node.name);
(node.children || []).forEach(child => getAllNames(child, list));
return list;
}
console.log('recursion', getAllNames(root));
//*/
const getAllNames2 = node => {
const list = [node.name],
stack = [{parent: node, index: 0}];
while (stack.length > 0) {
const frame = stack[stack.length - 1],
children = frame.parent.children || [];
if (frame.index < children.length) {
const nextChild = children[frame.index];
list.push(nextChild.name)
frame.index += 1;
stack.push({ parent: nextChild, index: 0 });
} else {
stack.pop();
}
}
return list;
}
console.log('loop', getAllNames2(root));