Last active
December 22, 2021 09:37
-
-
Save chengxiao/b83a4b97c874badf8f339a59d3e68a4b to your computer and use it in GitHub Desktop.
tree.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Data struct { | |
Id string `json:"id"` | |
Name string `json:"name"` | |
PId string `json:"p_id"` | |
Child []*Data `json:"child"` | |
} | |
type SliceData []*Data | |
func (s SliceData) Len() int { | |
return len(s) | |
} | |
func (s SliceData) Swap(i, j int) { | |
s[i], s[j] = s[j], s[i] | |
} | |
func (s SliceData) Less(i, j int) bool { | |
ii ,err:= strconv.Atoi(string([]byte(s[i].Id)[1:])) | |
if err != nil{ | |
return false | |
} | |
jj ,err:= strconv.Atoi(string([]byte(s[j].Id)[1:])) | |
if err != nil{ | |
return false | |
} | |
return ii<jj | |
} | |
func makeTree(Allnode []*Data, node *Data) { | |
childs, _ := haveChild(Allnode, node) //判断节点是否有子节点并返回 | |
if childs != nil { | |
node.Child = append(node.Child, childs[0:]...) //添加子节点 | |
for _, v := range childs { //查询子节点的子节点,并添加到子节点 | |
_, has := haveChild(Allnode, v) | |
if has { | |
makeTree(Allnode, v) //递归添加节点 | |
} | |
} | |
} | |
} | |
func haveChild(Allnode []*Data , node *Data ) (childs []*Data, yes bool) { | |
for _, v := range Allnode { | |
if v.PId == node.Id { | |
childs = append(childs, v) | |
} | |
} | |
if childs != nil { | |
yes = true | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment