中级农民
- 积分
- 103
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2023-6-27
- 最后登录
- 1970-1-1
|
2023(7-9月) 码农类General 本科 全职@bytedance - 内推 - 视频面试 | 😃 Positive 😐 Average | Pass | 其他
注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
本帖最后由 lglanan2023 于 2023-10-29 19:- 以下数据结构中,id 代表部门编号,name 是部门名称,parentId 是父部门编号,为 0 代表一级部门,现在要求实现一个 convert 方法,把原始 list 转换成树形结构,parentId 为多少就挂载在该 id 的属性 children 数组下,结构如下:
- // 原始 list 如下
- let list =[
- {id:1,name:'部门A',parentId:0},
- {id:2,name:'部门B',parentId:0},
- {id:3,name:'部门C',parentId:1},
- {id:4,name:'部门D',parentId:1},
- {id:5,name:'部门E',parentId:2},
- {id:6,name:'部门F',parentId:3},
- {id:7,name:'部门G',parentId:2},
- {id:8,name:'部门H',parentId:4}
- ];
- const result = convert(list, ...);
- // 转换后的结果如下
- let result = [
- {
- id: 1,
- name: '部门A',
- parentId: 0,
- children: [
- {
- id: 3,
- name: '部门C',
- parentId: 1,
- children: [
- {
- id: 6,
- name: '部门F',
- parentId: 3
- }, {
- id: 16,
- name: '部门L',
- parentId: 3
- }
- ]
- },
- {
- id: 4,
- name: '部门D',
- parentId: 1,
- children: [
- {
- id: 8,
- name: '部门H',
- parentId: 4
- }
- ]
- }
- ]
- },
- ···
- ];
复制代码- // 解答
- function buildOrganizationTree(employees) {
- const root = new TreeNode('root');
- const buildTree = (root, paths) => {
- if (paths.length == 0) return;
- if (paths.length > 0) {
- const p = paths.shift();
- root.children = root.children || [];
- let childNode = root.children.find(node => node && node.id === p);
- if (!childNode) {
- childNode = new TreeNode(p);
- root.children.push(childNode);
- }
- buildTree(childNode, paths);
- }
- }
- for (const person of employees) {
- const { department } = person;
- const dPaths = department.split('-');
- buildTree(root, dPaths);
- }
- return root;
- }
复制代码 |
上一篇: 字节一面下一篇: IBM BE intern OA
|