likes
comments
collection
share

【题目】扁平数据结构转Tree

作者站长头像
站长
· 阅读数 28

面试了十几个高级前端,竟然连(扁平数据结构转Tree)都写不出来

具体题目详情点击上面查看,树转扁平做得多,扁平转树还真没写过。有意思。上午看到做个笔迹记录下。扁平数据如下:

let arr = [
    {id: 1, name: '部门1', pid: 0},
    {id: 2, name: '部门2', pid: 1},
    {id: 3, name: '部门3', pid: 1},
    {id: 4, name: '部门4', pid: 3},
    {id: 5, name: '部门5', pid: 4},
]

输出结果如下,无限层级的树:

[
    {
        "id": 1,
        "name": "部门1",
        "pid": 0,
        "children": [
            {
                "id": 2,
                "name": "部门2",
                "pid": 1,
                "children": []
            },
            {
                "id": 3,
                "name": "部门3",
                "pid": 1,
                "children": [
                    // 结果 ,,,
                ]
            }
        ]
    }
]

自己写的解答方法

const flap2Tree = (flapArr)=>{
    //递归根据pid找父
    const findByPid = (pid, data)=> {
        for(let i=0; i<data.length; i++){
           if( data[i].id === pid ) {
               return data[i];
           }else if(data[i].children && data[i].children.length){
               return pidFindParent(pid, data[i].children);
           }
        }
    }

    let resTree = [];
    flapArr.forEach( t => {
        let myParent = findByPid(t.pid, afterArr); 
        if(myParent){
            myParent.children || (myParent.children = []); //初始化
            myParent.children.push(t);
        }else{
            resTree.push(t);
        }
    })
    return resTree;
}
flap2Tree(arr);

学习博主最优性能方法

function arrayToTree(items) {
  const result = [];   // 存放结果集
  const itemMap = {};  // 
  for (const item of items) {
    const id = item.id;
    const pid = item.pid;

    if (!itemMap[id]) {
      itemMap[id] = {
        children: [],
      }
    }

    itemMap[id] = {
      ...item,
      children: itemMap[id]['children']
    }

    const treeItem =  itemMap[id];

    if (pid === 0) {
      result.push(treeItem);
    } else {
      if (!itemMap[pid]) {
        itemMap[pid] = {
          children: [],
        }
      }
      itemMap[pid].children.push(treeItem)
    }

  }
  return result;
}