头图

利用栈实现树形结构转一维,效率可能更高,避免递归反复执行上下文引起的帧栈溢出

let tree = [
    {
        name: "home",
        meta: {
            title: "home",
            icon: "home"
        }
    },
    {
        name: "home2",
        meta: {
            title: "home",
            icon: "home"
        }
    },
    {
        name: "common-components",
        meta: {
            title: "common-components",
            icon: "set"
        },
        children: [
            {
                name: "form-component",
                meta: {
                    title: "form-component",
                    icon: "common"
                }
            }
        ]
    },
    {
        name: "multilevel-menu",
        meta: {
            title: "multilevel-menu",
            icon: "switch"
        },
        children: [
            {
                name: "second-menu",
                meta: {
                    title: "second-menu",
                    icon: "common"
                },
                children: [
                    {
                        name: "third-menu",
                        meta: {
                            title: "third-menu",
                            icon: "common"
                        }
                    }
                ]
            }
        ]
    }
]


function linearArray(nodes) {
    const result = [];
    while (nodes.length) {
        const next = nodes.pop();
        if (Array.isArray(next.children)) {
            nodes.push(...next.children);
        }
        result.push(next);
    }
    return result.reverse();
}

console.log(linearArray(tree)) 

image.png

1. 初始化
创建一个空数组result用来存储最终结果。
调用函数,传入树形数组nodes作为初始处理队列。

2. 循环处理每个节点
只要nodes数组中还有元素,就继续深度遍历:

  1. 弹出最后一个节点
    pop()nodes末尾取出一个节点。
  2. 处理子节点
    如果当前节点有children,将子节点依次添加到nodes末尾。
  3. 将当前节点存入结果
    将弹出的节点推入result数组。
  4. 反转结果
    循环结束后,result中的节点顺序是 深度优先遍历的逆序(后序遍历的反转)。为了恢复原始层级的顺序,调用result.reverse()反转数组。

兔子先森
465 声望205 粉丝

致力于新技术的推广与优秀技术的普及。