简体   繁体   中英

Convert list of nodes to a 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)

You have child nodes ([]Node) as value, not reference. So you add node 2 to node 1:

node1 -> node2

Then you add node3 to node2:

node2 -> node3

But since you have nodes by value, you never added node3 to the copy of node2 attached to node1, only to the node2 that is in the original array.

Change the declaration to:

Node []*Node

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM