I want to turn this recursion to loop, how can I do it?? I need to get the all name of the children, I did it in recursion, and I tried a lot of time to do it in loop, someone know how can I do it??
const Inode: INode = {
name: 'a',
children: [
{
name: 'b',
children: []
},
{
name: 'c',
children: [{
name: 'd',
children: []
},]
},
{
name: 'e',
children: []
},
]
}
const getAllNamesByRecursion = (Inode: INode) => {
console.log(Inode.name)
Inode.children.forEach((child) => {
if (Inode.children) {
return getAllNamesByRecursion(child);
}
})
}
As described in the comment, recursion can be imitated. In fact, machine language does not have recursion, so when compiled, a recursive function is implemented in exactly the same way: jumps (implementing a loop) and stack. Here is the solution in javascript , as tagged.
const inodes = { name: 'a', children: [ { name: 'b', children: [] }, { name: 'c', children: [ { name: 'd', children: [] }, ], }, { name: 'e', children: [] } ], }; function collectWithRecursion(fn, node) { return [ fn(node), ...(node.children?? []).flatMap(node => collectWithRecursion(fn, node)), ]; } function collectWithoutRecursion(fn, node) { // start with the top node in the stack const stack = [node]; const result = []; // repeat until the whole stack is processed while (stack.length) { // get the next node from the stack and process it const node = stack.pop(); result.push(fn(node)); // if the node has children, add them to the stack if (node.children) { stack.push(...node.children.reverse()); } } return result; } console.log("with recursion:", collectWithRecursion(node => node.name, inodes)); console.log("without recursion:", collectWithoutRecursion(node => node.name, inodes));
i,m not sure if i get ur question, but i think this is what u want to achieve? solution in js
const Inode = { name: 'a', children: [ { name: 'b', children: [] }, { name: 'c', children: [{ name: 'd', children: [] },] }, { name: 'e', children: [] }, ] } const getAllNamesByRecursion = (node) => { if (node.children) { return node.children.map((child) => child.name) } return null } console.log(getAllNamesByRecursion(Inode))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.