tree.go
933 字节
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
package domain
const (
StructTree = "tree"
StructList = "list"
)
type TreeNode interface {
PID() string
ID() string
}
type Tree struct {
Node TreeNode `json:"node"`
Nodes []*Tree `json:"nodes"`
}
func traverse(tree *Tree, node TreeNode) bool {
list := tree.Nodes
var match bool = false
for i := range list {
id, pid := list[i].Node.ID(), node.PID() //list[i].Node.PID() == node.ID()
if pid == id {
list[i].Nodes = append(list[i].Nodes, NewTree(node))
return true
}
if match || traverse(list[i], node) {
match = true
break
}
}
return match
}
func NewTrees(nodes []TreeNode) *Tree {
var tree = &Tree{
Node: nil,
Nodes: make([]*Tree, 0),
}
for i := range nodes {
match := traverse(tree, nodes[i])
if !match {
tree.Nodes = append(tree.Nodes, NewTree(nodes[i]))
}
}
return tree
}
func NewTree(node TreeNode) *Tree {
return &Tree{
Node: node,
Nodes: make([]*Tree, 0),
}
}