douweicheng5532
douweicheng5532
2019-08-16 22:13

将节点列表转换为图形

  • slice
  • tree
  • list
  • graph

I am trying to convert a list of nodes in Go to a graph representation. This example is a 1<- 2 <-3 structure but I always get a 1 <- 2 as the result and the 2<-3 is not included as it is not a parent node in the final list.How do I ensure that the reference is updated correctly for the child node's reference.

A node is defined like the struct below:

type Node struct {
    Name       string `json:"name"`
    UUID       string `json:"uuid"`
    ParentUUID string `json:"parentUuid"`
    ParentName string `json:"parentName"`
    Node       []Node
}

This is my implementation so far

func BuildTree(nodeList []models.Node) []models.Node {
    //build hashmap with reference to all nodes in the list
    nodeHashMap := make(map[string]NodeHash)
    for index, node := range nodeList {
        nodeHash := NodeHash{}
        nodeHash.NodeRef = &nodeList[index]
        nodeHash.Uid = node.UUID
        if len(node.ParentUUID) == 0 {
            nodeHash.IsParent = true
        }

        nodeHashMap[node.UUID] = nodeHash
    }

    //link all the nodes with parent nodes
    for _, node := range nodeList {
        if len(node.ParentUUID) != 0 {
            if parentHashNode, ok := nodeHashMap[node.ParentUUID]; ok {
                parentNodeRef := parentHashNode.NodeRef
                parentNodeRef.Node = append(parentNodeRef.Node, node)
            }
        }
    }

    //build a new list with only the parent nodes which is like the "root" level for the graph
    newNodeList := []models.Node{}
    for _, v := range nodeHashMap {
        if v.IsParent {
            newNodeList = append(newNodeList, *v.NodeRef)
        }
    }
    return newNodeList
}

I am trying to call this method like this:

node1 := models.Node{UUID:"1",Name: "parent"}
node2 := models.Node{UUID:"2",Name: "child",ParentUUID:"1"}
node3 := models.Node{UUID:"3",Name: "grandchild",ParentUUID:"2"}

nodeList := []models.Node{}
nodeList = append(nodeList,node1)
nodeList = append(nodeList,node2)
nodeList = append(nodeList,node3)
nodeTreeList := BuildTree(nodeList)
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答

为你推荐