查询从跟节点触发的每条路径

let _map = {
  9: {
    id: 9,
    list: [7]
  },
  7: {
    id: 7,
    list: [8, 6]
  },
  8: {
    id: 8,
    list: [2, 0]
  },
  2: {
    id: 2,
    list: null
  },
  0: {
    id: 0,
    list: null
  },
  6: {
    id: 6,
    list: [3, 5]
  },
  3: {
    id: 3,
    list: null
  },
  5: {
    id: 5,
    list: [4]
  },
  4: {
    id: 4,
    list: null
  }
}


function findPaths(obj) {
  let result = [];
  let path = [];
  if (obj == null) return result;
  getPath(obj, path, result);
  console.log('result', result)
}

function getPath(obj, path, result) {
  path.push(obj.id)
  if (obj.list === null) {
    result.push(path)
    return
  }

  for (var i = 0; i < obj.list.length; i++) {
    const p = Object.assign([], path)
    getPath(_map[obj.list[i]], p, result) // 回溯
  } 
}

findPaths(_map[9])

 

 

  

 

posted @ 2022-07-08 18:50  yewook  阅读(13)  评论(0编辑  收藏  举报