js手撕代码3:树形结构和列表结构相互转化(.ts)

下面分为两个部分:listToTree.ts 和 treeToList.ts

参考:集锦大厂面试常考的 前端手写题和 leetcode 算法题

如何直接运行 .ts 文件

第一步: npm install -g typescript

第二步(编译 TS → JS): tsc yourfile.ts

第三步(运行生成的.js文件): node yourfile.js

1. 列表和树形结构数据

// 列表结构

const listData = [

  { id: 1, text: '节点1', parentId: 0 },

  { id: 2, text: '节点1_1', parentId: 1 }

]

// 树形结构

const treeData = [

    {

        id: 1,

        text: '节点1',

        parentId: 0,

        children: [

            {

                id: 2,

                text: '节点1_1',

                parentId: 1

            }

        ]

    }

]

2.树形结构转成列表 treeToList.ts

interface DataItem{
    id:number,
    text:string,
    parentId:number,
    children?:DataItem[]
}

const treeData = [
    {
        id: 1,
        text: '节点1',
        parentId: 0,
        children: [
            {
                id: 2,
                text: '节点1_1',
                parentId: 1
            }
        ]
    }
]

function treeToList(data:DataItem[]){
    const res:DataItem[]=[];
    data.forEach(item=>dfs(item,res))
    
    function dfs(tree:DataItem,res:DataItem[]):void{
        const newTree={
            id:tree.id,
            text:tree.text,
            parentId:tree.parentId
        }
        res.push(newTree)
        if(tree.children){
            for(const item of tree.children){
                dfs(item,res)
            }
        }
    }
    return res
}

console.log(treeToList(treeData));

3.列表转成树形结构 listToTree.ts

interface DataItem{
    id:number,
    text:string,
    parentId:number
    children?:DataItem[]
}

const listData = [
  { id: 1, text: '节点1', parentId: 0 },
  { id: 2, text: '节点1_1', parentId: 1 }
]

// 时间复杂度O(n^2)
function listToTree1(data:DataItem[]):DataItem[]{
    const res:DataItem[]=[]
    data.forEach(item=>{
        const children_arr=data.filter(el=>{
            return item.id===el.parentId
        })
        if(children_arr.length>0){
            item.children=children_arr
        }
        if(item.parentId===0){
            res.push(item)
        }
    })
    return res
}

// 时间复杂度O(n)
function listToTree2(data:DataItem[]):DataItem[]{
    const res:DataItem[]=[]
    const hashmap:Record={}

    // 第一遍:创建所有节点的哈希表,并初始化 children 数组
    data.forEach(item => {
        hashmap[item.id] = { ...item, children: [] } 
    }) 
    
    // 第二遍:构建树结构
    data.forEach(item => {
        const { id, parentId } = item 
        
        if (parentId === 0) {
            // 根节点直接添加到结果
            res.push(hashmap[id]) 
        } else {
            // 处理子节点,添加到父节点的 children
            hashmap[parentId].children?.push(hashmap[id]) 
            } 
    }) 
    return res 
}


console.log(listToTree1(listData))
console.log(listToTree2(listData))


// const hashmap={
//     1:{id: 1, text: '节点1', parentId: 0, children:[]},
//     2:{id: 2, text: '节点1_1', parentId: 1, children:[]}
// }

你可能感兴趣的:(js手撕代码汇总,javascript,前端,typescript)