题目
扁平的数据结构,转成树。
打平的数据内容如下:
1 | let arr = [ |
[
{
“id”: 1,
“name”: “部门1”,
“pid”: 0,
“children”: [
{
“id”: 2,
“name”: “部门2”,
“pid”: 1,
“children”: []
},
{
“id”: 3,
“name”: “部门3”,
“pid”: 1,
“children”: [
// 结果 ,,,
]
}
]
}
]
1 |
|
/**
- 递归查找,获取children
- /
const getChildren = (data, result, pid) => {
for (const item of data) {
if (item.pid === pid) {
}const newItem = {...item, children: []}; result.push(newItem); getChildren(data, newItem.children, item.id);
}
}
/**
- 转换方法
- /
const arrayToTree = (data, pid) => {
const result = [];
getChildren(data, result, pid)
return result;
}
1 | 时间复杂度为`O(2^n)`。 |
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;
}
1 | 时间复杂度为`O(2n)`,需要一个Map把数据存储起来,空间复杂度`O(n)` |
function arrayToTree(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;
}