SOURCE

// 输入c121 得到[root, c1, c12]
const tree = {
    name: 'root',
    children: [
        {
            name: 'c1',
            children: [
                {
                    name: 'c11',
                    children: []
                },
                {
                    name: 'c12',
                    children: [
                        {
                            name: 'c121',
                            children: []
                        }
                    ],
                },
                {
                    name: 'c13',
                    children: []
                }
            ]
        },
        {
            name: 'c2',
            children: [
                {
                    name: 'c21',
                    children: []
                },
                {
                    name: 'c22',
                    children: []
                }
            ]
        }
    ]
}
// 深度优先 记录路径节点
const dfs = (source, name) => {
    let stack = []
    stack.push(source)
    while (stack.length) {
        let node = stack.pop()
        if(name === node.name){
            return node.path ? node.path.split('-') : null
        }
        for (let i = node.children.length - 1; i >= 0; i--) {
            const path = node.path ? `${node.path}-${node.name}` : node.name
            stack.push({...node.children[i], path})
        }
    }
    return null
}

console.log(dfs(tree, 'c121'))
console 命令行工具 X clear

                    
>
console