golang 面试题
// 在线面试平台。将链接分享给你的朋友以加入相同的房间。
[
{id:1, pid:0},
{id:2, pid:1},
{id:3, pid:2},
{id:10, pid:1},
{id:11, pid:0},
{id:12, pid:11},
{id:6, pid:11},
{id:8, pid:2},
...
];
{id:1, pid:0},表示序号1的父亲节点是0,
[
{id:1, child:[
{id:2, child:[
{id:3, child:[...]},
]},
{id:10, child:[...]}
]},
{id:11, child:[...]},
...
]
package main
import "fmt"
//定义一个分类结构体
type Category struct{
id int
pid int //父id
Children []*Category
}
//构建一个分类
func buildCategoryTree(categorys []Category, paretId int) []Category{
var tree []*Category
for _, category := range categorys {
if category.pid == paretId {
category.Children = buildCategoryTree(categorys, category.id)
tree = append(tree, category)
}
}
return tree
}
func main(){
categorys := []Category{
{id:1, pid:0},
{id:2, pid:1},
{id:3, pid:2},
{id:10, pid:1},
{id:11, pid:0},
{id:12, pid:11},
{id:6, pid:11},
{id:8, pid:2},
}
tree := buildCategoryTree(categorys, 0)
fmt.Println(tree)
];
}
浙公网安备 33010602011771号