JS算法-数组与树状结构的转换

154 阅读1分钟

最近被到几次比较高频的算法面试题,如何实现数组转树状结构。

数组转树状结构

例如:

const arr = [
  {id: 1, pid: 0},
  {id: 2, pid: 1},
  {id: 3, pid: 2},
  {id: 4, pid: 1},
  {id: 5, pid: 0},
  {id: 6, pid: 5}
]

输出结果为 =>

const tree = {
  {
    id: 1,
    children: [
      {
        id: 2,
        children: [
          {
            id: 3,
            chidlren: []
          }
        ]
      },
      {
        id: 4,
        children: []
      }
    ]
  },
  {
    id: 5,
    children: [
      {
        id: 6,
        children: []
      }
    ]
  }
}

实现方案:

const arr = [
  {id: 1, pid: 0},
  {id: 2, pid: 1},
  {id: 3, pid: 2},
  {id: 4, pid: 1},
  {id: 5, pid: 0},
  {id: 6, pid: 5}
]
function listToTree(arr) {
  const tree = [];
  const toTree = function(arr, tree, id) {
    arr.forEach(item => {
      if(item.pid === id) {
        const obj = {
          id: item.id,
          children: []
        };
        toTree(arr, obj.children, item.id);
        tree.push(obj);
      }  
    });
  }
  toTree(arr, tree, 0);
  return tree;
}
console.log(listToTree(arr));

总结

个人感觉,递归思想在编程中还是很重要的。