美文网首页
扁平数据结构转Tree

扁平数据结构转Tree

作者: likeli | 来源:发表于2022-11-24 16:51 被阅读0次
    let arr = [
        {id: 1, name: '部门1', pid: 0},
        {id: 2, name: '部门2', pid: 1},
        {id: 3, name: '部门3', pid: 1},
        {id: 6, name: '部门3', pid: 2},
        {id: 4, name: '部门4', pid: 3},
        {id: 7, name: '部门4', pid: 3},
        {id: 5, name: '部门5', pid: 4},
    ]
    

    自己写的方法,使用递归方式

    //第一步选取根结点
    const getData = arr.filter(v => !arr.some((item) => item.id === v.pid))
    let length = getData.length
    // 递归循环处理数据
    function returnData(result, pid){
        arr.filter( val=>{
            if(val.pid!=result.pid) {
                if (pid == val.pid) {
                    if (!result.children) {
                        result.children = []
                    }
                    result.children.push(val)
                    length++
                    if(length<=arr.length){
                        returnData(val, val.id)
                    }
                }
            }
        })
    }
    getData.filter(item=>{
        returnData(item,item.id)
    })
    

    网上借鉴的方法(该实现的时间复杂度为O(2n))

    function arrayToTree(items) {
        const result = [];   // 存放结果集
        const itemMap = {};  //
        // 先转成map存储
        for (const item of items) {
            itemMap[item.id] = {...item, children: []}
        }
        for (const item of items) {
            const id = item.id;
            const pid = item.pid;
            const treeItem =  itemMap[id];
            if (pid === 0) {
                result.push(treeItem);
            } else {
                if (!itemMap[pid]) {
                    itemMap[pid] = {
                        children: [],
                    }
                }
                itemMap[pid].children.push(treeItem)
            }
        }
        return result;
    }
    

    网上借鉴的方法(该实现的时间复杂度为O(n))

    function arrayToTree1(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;
    }
    

    相关文章

      网友评论

          本文标题:扁平数据结构转Tree

          本文链接:https://www.haomeiwen.com/subject/cqizxdtx.html