递归是最简单的方案,单递归不是最佳的方案
平转树不使用递归
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58const arr = [
{
"id": 3,
"name": "部门3",
"pid": 2
},
{
"id": 4,
"name": "部门4",
"pid": 3
},
{
"id": 5,
"name": "部门5",
"pid": 4
},
{
"id": 1,
"name": "部门1",
"pid": 0
},
{
"id": 2,
"name": "部门2",
"pid": 1
}
]
function arrayToTree(items) {
const result = []
const hashMap = {}
for (const item of items) {
const id = item.id
const pid = item.pid
hashMap[id] = { ...item, children: [] }
console.log('id :>> ', id);
console.log('pid :>> ', pid);
const newItem = hashMap[id]
if (pid === 0) {
result.push(newItem)
} else {
if (!hashMap[pid]) {
hashMap[pid] = { children: [] }
}
hashMap[pid]['children'].push(newItem)
}
console.log('------------------')
}
return result
}
const treeObj = arrayToTree(arr)
console.log(JSON.stringify(treeObj, null, ' '));树遍历不使用递归
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53const data = [{
label: '一级 1',
children: [{
label: '二级 1-1',
children: [{
label: '三级 1-1-1'
}]
}]
}, {
label: '一级 2',
children: [{
label: '二级 2-1',
children: [{
label: '三级 2-1-1'
}]
}, {
label: '二级 2-2',
children: [{
label: '三级 2-2-1'
}]
}]
}, {
label: '一级 3',
children: [{
label: '二级 3-1',
children: [{
label: '三级 3-1-1'
}]
}, {
label: '二级 3-2',
children: [{
label: '三级 3-2-1'
}]
}]
}]
function start(data) {
let list = [...data]
while (list.length) {
const first = list.shift()
console.log('first :>> ', first.label);
const children = first.children
if (children && children.length) {
list = list.concat(children)
}
}
}
start(data)