douweicheng5532 2019-08-16 22:13
浏览 163
已采纳

将节点列表转换为图形

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条回答 默认 最新

  • dongsha1544 2019-08-16 22:40
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器