Skip to content

Instantly share code, notes, and snippets.

@carmel
Last active February 10, 2021 00:52
Show Gist options
  • Save carmel/43b6bc7569829e85792ec008197c8222 to your computer and use it in GitHub Desktop.
Save carmel/43b6bc7569829e85792ec008197c8222 to your computer and use it in GitHub Desktop.
Converts an array of items with ids and parent ids to a nested tree in a performant way
type TreeNode struct {
Id string
Name string
Pid string
Sub []*TreeNode
}
func CreateDataTree(data []TreeNode, maxDepth int) []*TreeNode {
var hash = map[string]*TreeNode{}
for i := range data {
// 注意使用`for i, v := range`形式时,迭代变量v的地址始终指向同一个
hash[data[i].Id] = &data[i]
}
var (
ok bool
node *TreeNode
)
var dataTree = make([]*TreeNode, 0, maxDepth)
for i := range data {
if node, ok = hash[data[i].Pid]; ok {
if len(node.Sub) == 0 {
node.Sub = make([]*TreeNode, 0, maxDepth)
}
node.Sub = append(node.Sub, hash[data[i].Id])
} else {
dataTree = append(dataTree, hash[data[i].Id])
}
}
return dataTree
}
data := []TreeNode{
{
Id: "/1/",
Pid: "/",
Name: "上衣",
},
{
Id: "/2/",
Pid: "/",
Name: "裤子",
},
{
Id: "/1/3/",
Pid: "/1/",
Name: "夹克",
},
{
Id: "/1/4/",
Pid: "/1/",
Name: "西装",
},
{
Id: "/2/5/",
Pid: "/2/",
Name: "运动裤",
},
{
Id: "/2/6/",
Pid: "/2/",
Name: "牛仔裤",
},
{
Id: "/1/4/7/",
Pid: "/1/4/",
Name: "中式西装",
},
}
dataTree := CreateDataTree(data, 10)
// fmt.Println(dataTree[0].Sub[0].Name)
// fmt.Println(dataTree[0].Sub[1].Sub[0].Name)
fmt.Printf("%+v\n", dataTree)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment