SOURCE

let lifeCycle = [
    {
        name: '页面加载时执行',
        id: 'onLoadTree',
        list: [
            {
                id: 1,
                name: "1",
                options: {
                    disabled: true,
                },
                list: []
            },
            {
                id: 2,
                name: "2",
                options: {
                    disabled: true,
                },
                list: [
                    {
                        id: 4,
                        name: "4",
                        options: {

                        },
                        list: []
                    },

                ]
            },

        ]
    },
    {
        name: '页面显示时执行',
        id: 'onShowTree',
        list: [
            {
                id: 3,
                name: "3",
                options: {
                    disabled: true,
                },
                list: [
                    {
                        id: 5,
                        name: "5",
                        options: {
                            disabled: true,
                        },
                        list: []
                    }
                ]
            }
        ]
    }

]

// function traverseTree(root) {
//   const stack = root

//   while (stack.length > 0) {
//     const node = stack.pop();
//     // 处理当前节点
//     console.log(node.name);
//     // 将子节点逆序压入栈
//     if (node.list) {
//       stack.push(...node.list.reverse());
//     }
//   }
// }

function traverseTreeDFS(root) {
    const stack = [{ node: root, parent: null, index: -1 }];

    while (stack.length > 0) {
        const { node, parent, index } = stack.pop();
        // 处理当前节点
        console.log(node.name);
        // console.log('Parent:', parent);
        console.log('Index:', index);

        // 将子节点逆序压入栈,并记录父节点及索引信息
        if (node.list) {
            const children = node.list
            for (let i = 0; i < children.length; i++) {
                stack.push({ node: children[i], parent: node, index: i });
            }
        }
    }
}

for (let item of lifeCycle) {
    traverseTreeDFS(item)
}





console 命令行工具 X clear

                    
>
console