go语言实现递归,扁平转为树形,同时添加层级标识

原始数据结构

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
[
{
"id": "1",
"pid": "0"
},
{
"id": "2",
"pid": "1"
},
{
"id": "3",
"pid": "1"
},
{
"id": "4",
"pid": "0"
},
{
"id": "5",
"pid": "4"
},
{
"id": "6",
"pid": "4"
},
{
"id": "7",
"pid": "3"
},
{
"id": "8",
"pid": "3"
}
]

目标数据结构

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
[
{
"id": "1",
"pid": "0",
"level": 0,
"children": [
{
"id": "2",
"pid": "1",
"level": 1
},
{
"id": "3",
"pid": "1",
"level": 1,
"children": [
{
"id": "7",
"pid": "3",
"level": 2
},
{
"id": "8",
"pid": "3",
"level": 2
}
]
}
]
},
{
"id": "4",
"pid": "0",
"level": 0,
"children": [
{
"id": "5",
"pid": "4",
"level": 1
},
{
"id": "6",
"pid": "4",
"level": 1
}
]
}
]

go 实现的核心函数

指定pid根节点和level根层标识

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func handle(pid string, level int8) []d {
var tree []d
for _, v := range data {
if v.Pid == pid {
var children []d
children = append(children, handle(v.ID, level+1)...)
tree = append(tree, d{
Level: level,
ID: v.ID,
Pid: v.Pid,
Children: children,
})
}
}
return tree
}

完整代码,粘贴即可运行

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main

import (
"bytes"
"encoding/json"
"log"
"os"
)

type dataSource struct {
ID string `json:"id"`
Pid string `json:"pid"`
}

type d struct {
Level int8 `json:"level"`
ID string `json:"id"`
Pid string `json:"pid"`
Children []d `json:"children"`
}

var data = []*dataSource{
{
ID: "1",
Pid: "0",
},
{
ID: "2",
Pid: "1",
},
{
ID: "3",
Pid: "1",
}, {
ID: "4",
Pid: "0",
}, {
ID: "5",
Pid: "4",
},
{
ID: "6",
Pid: "4",
},
{
ID: "7",
Pid: "3",
},
{
ID: "8",
Pid: "3",
},
}

func handle(pid string, level int8) []d {
var tree []d
for _, v := range data {
if v.Pid == pid {
var children []d
children = append(children, handle(v.ID, level+1)...)
tree = append(tree, d{
Level: level,
ID: v.ID,
Pid: v.Pid,
Children: children,
})
}
}
return tree
}

func main() {
root := handle("0", 0)
b, _ := json.Marshal(root)

var out bytes.Buffer
err := json.Indent(&out, b, "", "\t")

if err != nil {
log.Fatalln(err)
}

out.WriteTo(os.Stdout)
}

输出结果

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
[
{
"level": 0,
"id": "1",
"pid": "0",
"children": [
{
"level": 1,
"id": "2",
"pid": "1",
"children": null
},
{
"level": 1,
"id": "3",
"pid": "1",
"children": [
{
"level": 2,
"id": "7",
"pid": "3",
"children": null
},
{
"level": 2,
"id": "8",
"pid": "3",
"children": null
}
]
}
]
},
{
"level": 0,
"id": "4",
"pid": "0",
"children": [
{
"level": 1,
"id": "5",
"pid": "4",
"children": null
},
{
"level": 1,
"id": "6",
"pid": "4",
"children": null
}
]
}
]