简体   繁体   English

如何将递归转换为循环

[英]how can I turn recursion to a loop

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.事实上,机器语言没有递归,所以在编译时,递归的 function 的实现方式完全相同:跳转(实现循环)和堆栈。 Here is the solution in , 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 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM