获取树结构所有路径?
有一下树形数据:
const data= [
{
label: 'Level one 1',
children: [
{
label: 'Level two 1-1',
children: [
{
label: 'Level three 1-1-1',
},
],
},
],
},
{
label: 'Level one 2',
children: [
{
label: 'Level two 2-1',
children: [
{
label: 'Level three 2-1-1',
},
],
},
],
}
]
期望输出所有叶子节点的路径:
["Level one 1 > Level two 1-1 > Level three 1-1-1", "Level one 2 > Level two 2-1 > Level three 2-1-1"]
回复
1个回答

test
2024-07-12
其实就是树的先序遍历
function preOrder(list, result=[], labels=[]) {
return list.reduce((res,v) => {
labels.push(v.label);
if(v.children && v.children.length) preOrder(v.children, res, labels);
else res.push(labels.join(' > '))
labels.pop();
return res;
}, result)
}
preOrder(data)
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容