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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| package work
import "fmt"
type lable struct { id int name string parentId int son []*lable }
var lables = [...]*lable{{ id: 1, name: " 爷爷 ", parentId: 0, }, { id: 2, name: " 姥姥 ", parentId: 0, }, { id: 3, name: " 父亲 ", parentId: 1, }, { id: 4, name: " 母亲 ", parentId: 2, }, { id: 5, name: " 大儿子 ", parentId: 3, }, { id: 6, name: " 二儿子 ", parentId: 4, }}
func buildLabelData(list []*lable) map[int]map[int]*lable { var data = make(map[int]map[int]*lable) for _, val := range list { id := val.id parentId := val.parentId if _, ok := data[parentId]; !ok { data[parentId] = make(map[int]*lable) } data[parentId][id] = val } return data }
func makeTreeLabel(index int, data map[int]map[int]*lable) []*lable { tmp := make([]*lable, 0) for id, item := range data[index] { if data[id] != nil { item.son = makeTreeLabel(id, data) } else { item.son = []*lable{} } tmp = append(tmp, item) } return tmp }
func lastOperate(labs []*lable) [][]string { var lastData [][]string for _, f := range labs { for _, s := range f.son { for _, t := range s.son { tmpData := []string{ f.name, s.name, t.name, } lastData = append(lastData, tmpData) } } } return lastData }
func Entrance() { data := buildLabelData(lables[:]) labs := makeTreeLabel(0, data) lastData := lastOperate(labs) for _, slices := range lastData { for _, dada := range slices { fmt.Printf("%s\t", dada) } fmt.Println() } }
|