其他分享
首页 > 其他分享> > 查询从跟节点触发的每条路径

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

作者:互联网

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])

 

 

  

 

标签:触发,obj,list,每条,id,result,path,null,节点
来源: https://www.cnblogs.com/yewook/p/16459392.html