golang 面试题-递归

package main

import (
"encoding/json"
"fmt"
)

// Category 结构体代表单个分类
type Category struct {
ID int
Name string
ParentID int
Children []*Category
}

// 递归函数用于构建分类树
func buildCategoryTree(categories []Category, parentID int) []Category {
var tree []*Category
for _, category := range categories {
if category.ParentID == parentID {
category.Children = buildCategoryTree(categories, category.ID)
tree = append(tree, category)
}
}
return tree
}

func printCategory(category *Category, level int) {
indent := ""
for i := 0; i < level; i++ {
indent += " "
}
fmt.Println(indent, category.Name)
for _, child := range category.Children {
printCategory(child, level+1)
}
}

func main() {
// 示例分类数据
categories := []*Category{
{ID: 1, Name: "电子产品", ParentID: 0},
{ID: 2, Name: "手机", ParentID: 1},
{ID: 3, Name: "笔记本电脑", ParentID: 1},
{ID: 4, Name: "家电", ParentID: 0},
{ID: 5, Name: "电视", ParentID: 4},
{ID: 6, Name: "手机配件", ParentID: 2},
}

// 构建分类树
tree := buildCategoryTree(categories, 0)
for _, v := range tree{
     // fmt.Println(k,v)
     printCategory(v, 0)
}

// fmt.Println(string(tree))

// 输出分类树的JSON表示
result, _ := json.MarshalIndent(tree, "", "  ")
fmt.Println(string(result))

}

posted @ 2024-07-03 22:41  北京小小鸟  阅读(10)  评论(0)    收藏  举报