Js 扁平数据转树

let arr = [
    {id:1,pid:-1},
    {id:2,pid:-1},
    {id:3,pid:-1},
    {id:4,pid:2},
    {id:5,pid:1},
    {id:6,pid:3},
    {id:7,pid:4},
    {id:7,pid:3},
]

基础数据如上

递归方法,时间复杂度根据递归的深度(k)为n的k次方

function arrToTree1(arr,root){
    let array = [];
    arr.forEach(item => {
        if(item.pid===root){
            item.children = arrToTree1(arr,item.id)
            if(item.children.length===0)
                delete item.children
            array.push(item)
        }
    });
    return array;
}

利用双循环判断,时间复杂度为n的平方

function arrToTree2(arr,root){

    let tree = JSON.parse(JSON.stringify(arr))
   
    let array = [] 

    array = tree.filter((father=>{  

        father.children  =  tree.filter((children)=>{

            return father.id === children.pid

        })

        if(father.children.length===0)
            delete father.children

        return father.pid === root
    }))

    return array;
}

利用map保存数据,时间复杂度为n

function arrToTree3(arr,root){

    let map = {};
    let array = [];

    arr.forEach(item=>{
        map[item.id] =item
    })

    arr.forEach((item)=>{
        if(item.pid===root)
            array.push(item);
        else{
            if(map[item.pid].children){
                map[item.pid].children.push(item)
            }else{
                map[item.pid].children=[item]
            }
        }
    })

    return array
}

你可能感兴趣的:(js,数据结构,算法,数据结构,json)