Middle
Task: traverse a tree with output text with indentation (recursive traversal of a nested list)
sobes.tech AI
Answer from AI
To perform a recursive tree traversal with indented text output, you can use a function that takes a node and a level of depth. At each level, add indentation, for example, using spaces or tabs.
Here's an example in JavaScript for a nested list of objects:
function printTree(node, indent = 0) {
console.log(' '.repeat(indent) + node.text);
if (node.children) {
node.children.forEach(child => printTree(child, indent + 2));
}
}
// Example data
const tree = {
text: 'root',
children: [
{ text: 'child1' },
{ text: 'child2', children: [
{ text: 'grandchild1' },
{ text: 'grandchild2' }
]}
]
};
printTree(tree);
The output will have indents reflecting the depth of nesting:
root
child1
child2
grandchild1
grandchild2
This approach is versatile and easily adaptable to different structures and output formats.