判断有无符合路径和 -> 打印所有路径
Sunny-117 opened this issue · comments
const data3 = [
{
id: 1,
name: '前端',
children: [
{
id: 2,
name: 'html',
children: [
{ id: 5, name: 'vue', children: [] },
{ id: 6, name: 're', children: [] },
]
},
{
id: 3,
name: 'html',
children: [
{ id: 7, name: 'vue', children: [] },
{ id: 8, name: 're', children: [] },
]
}
]
}
]
function findNodePath(data, targetName) {
let result = [];
function dfs(node, path) {
if (node.name === targetName) {
result.push(path.concat(node.id));
}
if (node.children) {
for (let child of node.children) {
dfs(child, path.concat(node.id));
}
}
}
for (let node of data) {
dfs(node, []);
}
return result;
}
console.log(findNodePath(data3, 'vue')); // [[1, 2, 5], [1, 3, 7]]
console.log(findNodePath(data3, 're')); // [[1, 2, 6], [1, 3, 8]]