有这样的一组节点,每个节点包含自己的Id,还有父Id (Parent Id),包含children指针数组,但是children是空,需要根据id和parentId把cihldren填充上。
实现了如下的方法
type TreeNode interface {
ID() int
ParentID() int
AppendChildren(interface{})
}
func BuildTree(array []TreeNode) TreeNode {
maxLen := len(array)
var rootNode TreeNode = nil
///<找出根节点,根节点的特点,没有父节点
for i := 0; i < maxLen; i++ {
///< 统计每个节点的父节点出现的次数,父节点出现0次就是根节点
count := 0
for j := 0; j < maxLen; j++ {
///< 如果有节点的ID == i的parentID 那么j就是父节点
if array[j].ID() == array[i].ParentID() {
count++
array[j].AppendChildren(array[i])
}
}
if count == 0 {
rootNode = array[i]
}
}
return rootNode
}
以下是测试使用的方法
type DataNode struct {
Id int `json:"id"`
ParentId int `json:"parentId"`
Children []*DataNode `json:"children"`
}
func (d *DataNode) ID() int {
return d.Id
}
func (d *DataNode) ParentID() int {
return d.ParentId
}
func (d *DataNode) AppendChildren(node interface{}) {
d.Children = append(d.Children, node.(*DataNode))
}
func TestBuildTree(t *testing.T) {
dataArr := []DataNode{
DataNode{
Id: 1,
ParentId: 0,
},
DataNode{
Id: 2,
ParentId: 1,
},
DataNode{
Id: 3,
ParentId: 1,
},
DataNode{
Id: 4,
ParentId: 1,
},
DataNode{
Id: 5,
ParentId: 2,
},
DataNode{
Id: 6,
ParentId: 2,
},
DataNode{
Id: 7,
ParentId: 3,
},
DataNode{
Id: 8,
ParentId: 3,
},
DataNode{
Id: 9,
ParentId: 3,
},
}
nodeArray := make([]TreeNode, len(dataArr))
for i := 0; i < len(dataArr); i++ {
nodeArray[i] = &dataArr[i]
}
rootNode := BuildTree(nodeArray)
rootNodeByte, err := json.Marshal(rootNode)
retStr := string(rootNodeByte)
if err != nil {
t.Fail()
} else {
if retStr == `{"id":1,"parentId":0,"children":[{"id":2,"parentId":1,"children":[{"id":5,"parentId":2,"children":null},{"id":6,"parentId":2,"children":null}]},{"id":3,"parentId":1,"children":[{"id":7,"parentId":3,"children":null},{"id":8,"parentId":3,"children":null},{"id":9,"parentId":3,"children":null}]},{"id":4,"parentId":1,"children":null}]}` {
t.Log("pass")
} else {
t.Fail()
}
}
}