// Дана вложенная структура файлов и папок.
 
const data = {
name: 'folder',
children: [
{ name: 'file1.txt' },
{ name: 'file2.txt' },
{
name: 'images',
children: [
{ name: 'image.png' },
{
name: 'vacation',
children: [{ name: 'crocodile.png' }, { name: 'penguin.png' }],
},
],
},
{ name: 'shopping-list.pdf' },
],
};
 
function printFileTree2(tree) {
const stack = [{ ...tree, level: 0 }];
let printed = '';
 
while (stack.length) {
const node = stack.pop();
 
const name = node.name;
const level = node.level;
const children = node.children;
 
printed += `${' '.repeat(level)}${name}\n`;
 
if (children) {
for (let i = children.length - 1; i >= 0; i--) {
const child = children[i];
 
stack.push({
name: child.name,
level: level + 1,
children: child.children,
});
}
}
}
 
return printed;
}
 
console.log(printFileTree2(data));
 
/*
Нужно вывести в консоль файлы и папки с отступами, чтобы показать вложенность.
Решение должно учитывать любую вложенность элементов (т.е. не должно содержать рекурсивные вызовы).
*/
 
/*
Пример вывода:
folder
file1.txt
file2.txt
images
image.png
vacation
crocodile.png
penguin.png
shopping-list.pdf
*/
 
function printFileTree(root) {
const stack = [{ ...root, level: 0 }];
 
while (stack.length) {
const node = stack.pop();
 
const name = node.name;
const level = node.level;
const children = node.children;
 
console.log(' '.repeat(level * 2) + name);
 
if (children) {
for (let i = children.length - 1; i >= 0; i--) {
const child = children[i];
 
stack.push({
name: child.name,
children: child.children,
level: level + 1,
});
}
}
}
}
 
printFileTree(data);
 
Click Run to execute JavaScript.
Code runs in an isolated environment.