簡體   English   中英

如何將遞歸轉換為循環

[英]how can I turn recursion to a loop

我想把這個遞歸變成循環,我該怎么做? 我需要得到孩子的全名,我是遞歸做的,我嘗試了很多時間循環做,有人知道我該怎么做嗎?

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);
        }
    })

}

如評論中所述,可以模仿遞歸。 事實上,機器語言沒有遞歸,所以在編譯時,遞歸的 function 的實現方式完全相同:跳轉(實現循環)和堆棧。 這是中的解決方案,已標記。

 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));

我不確定我是否得到你的問題,但我認為這就是你想要實現的目標? 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