Sunny-117/js-challenges

判断有无符合路径和 -> 打印所有路径

Sunny-117 opened this issue · 2 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]]
function fn(arr, name, path = '', res = []) {
    if (!arr) return null
    for (const item of arr) {
        if (item.name == name) {
            res.push(path ? path + '->' + item.id : item.id)
        } else {
            if (item.children && item.children.length) {
                fn(item.children, name, path ? path + '->' + item.id : item.id, res)
            }
        }
    }
    return res
}