Wiidede's blog Wiidede's blog
  • 前端
  • Python
  • 算法
  • 生活
  • 其他
  • 分类
  • 标签
  • 归档
  • 关于我
  • 赞赏
  • 我的小站 (opens new window)
GitHub (opens new window)

Wiidede

小的的写前端
  • 前端
  • Python
  • 算法
  • 生活
  • 其他
  • 分类
  • 标签
  • 归档
  • 关于我
  • 赞赏
  • 我的小站 (opens new window)
GitHub (opens new window)
  • leetcode-cn-40-组合总和 II 以及回溯
  • leetcode-cn-115-不同的子序列
  • 掘金上的小题目
    • 扁平数据结构转Tree题目
  • 算法
wiidede
2022-01-10

掘金上的小题目

# 掘金上的小题目

# 扁平数据结构转Tree题目 (opens new window)

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},
]

const arrayToTree = (arr) => {
    const map = {}; // 使用map快速通过找到id找到某一项
    const arrWithChildren = arr.map((item) => {
        const res = {...item};
        res.children = [];
        map[res.id] = res;
        return res;
    })

    const tree = [];

    arrWithChildren.forEach((item) => {
        const parent = map[item.pid];
        if (!parent) {
            tree.push(item);
            return;
        }

        parent.children.push(item);
    })

    return tree;
}

arrayToTree(arr);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

没想到真的在实际开发中用到了,优化一下写法抽出来吧,顺便优化树的结构,添加parent查看parent节点

const arr2tree = (arr, idKey = 'id', parentIdKey = 'parentId', childrenKey = 'children') => {
  const map = {};
  const tree = [];
  arr.map((item) => {
    const res = {...item, [childrenKey]: []};
    map[res[idKey]] = res;
    return res;
  }).forEach((item) => {
    const parent = map[item[parentIdKey]];
    item[parentKey] = parent;
    parent ? parent[childrenKey].push(item) : tree.push(item);
  });
  return tree;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14

为了进一步优化树的结构,给每一个节点遍历加上根节点id

const addRootId = (arr, rootIdKey = 'rootId', idKey = 'id', childrenKey = 'children') => {
  const traverse = (node, rootId) => {
    node[rootIdKey] = rootId;
    node[childrenKey] && node[childrenKey].forEach(child => traverse(child, rootId));
  };
  arr.forEach(root => {
    traverse(root, root[idKey]);
  });
};
1
2
3
4
5
6
7
8
9
#算法
上次更新: 2023/06/01, 12:40:50

← leetcode-cn-115-不同的子序列

Theme by Vdoing | Copyright © 2021-2023 Wiidede | Website use MIT License | Article content & logo use CC-BY-SA-4.0 License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式