Go递归实现树状数据

Code

package main

import "fmt"

type SourceData struct {
    Id   int
    Pid  int
    Name string
}

type TreeData struct {
    Id    int
    Name  string
    Child []TreeData
}

func main() {
    var sourceData []SourceData
    sourceData = append(sourceData, SourceData{
        Id:   1,
        Pid:  0,
        Name: "北京市",
    }, SourceData{
        Id:   2,
        Pid:  1,
        Name: "北京市",
    }, SourceData{
        Id:   3,
        Pid:  2,
        Name: "通州区",
    }, SourceData{
        Id:   4,
        Pid:  2,
        Name: "朝阳区",
    }, SourceData{
        Id:   5,
        Pid:  2,
        Name: "海淀区",
    }, SourceData{
        Id:   6,
        Pid:  0,
        Name: "河北省",
    }, SourceData{
        Id:   7,
        Pid:  6,
        Name: "廊坊市",
    }, SourceData{
        Id:   8,
        Pid:  7,
        Name: "三河市",
    }, SourceData{
        Id:   9,
        Pid:  8,
        Name: "燕郊镇",
    }, SourceData{
        Id:   10,
        Pid:  8,
        Name: "高楼镇",
    }, SourceData{
        Id:   11,
        Pid:  0,
        Name: "辽宁省",
    }, SourceData{
        Id:   12,
        Pid:  11,
        Name: "朝阳市",
    }, SourceData{
        Id:   13,
        Pid:  12,
        Name: "凌源市",
    }, SourceData{
        Id:   14,
        Pid:  13,
        Name: "四合当镇",
    }, SourceData{
        Id:   15,
        Pid:  13,
        Name: "三家镇",
    })

    treeData := getTree(sourceData, 0)
    fmt.Printf("%+v\n", treeData)
}

func getTree(data []SourceData, pid int) (resp []TreeData) {
    for _, v := range data {
        if v.Pid == pid {
            resp = append(resp, TreeData{
                Id:    v.Id,
                Name:  v.Name,
                Child: getTree(data, v.Id),
            })
        }
    }
    return resp
}

记录一下

打赏
评论区
头像
    头像
    心月云
      

    没学过GO,看不懂~