【问题标题】:Convert list of nodes to a graph将节点列表转换为图形
【发布时间】:2019-12-23 04:40:57
【问题描述】:

我正在尝试将 Go 中的节点列表转换为图形表示。 这个例子是一个 1

节点定义如下:

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

这是我目前的实现

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
}

我正在尝试这样调用此方法:

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)

【问题讨论】:

  • 对不起..它完成了!
  • 您改进了缩进,但代码仍然非常难看/难以阅读。请使用goftmt。我为你做了更多的修饰。
  • 使用 gofmt 更新。

标签: list go graph tree slice


【解决方案1】:

您将子节点 ([]Node) 作为值,而不是引用。所以你将节点 2 添加到节点 1:

节点1 -> 节点2

然后将node3添加到node2:

节点2 -> 节点3

但由于您有节点值,因此您从未将 node3 添加到附加到 node1 的 node2 的副本中,仅添加到原始数组中的 node2 中。

将声明更改为:

Node []*Node

【讨论】:

  • 谢谢..但地图不应该已经包含所有参考吗?
  • @DntFrgtDSemiCln:您的地图引用了原始节点。您的返回值是不使用原始节点的新节点的新副本。新副本也不指附加的新副本。你有很多副本在这里发生!
  • @DntFrgtDSemiCln 地图有参考,但没有节点。每个节点都包含另一个节点的副本,而不是对该节点的引用。所以节点1包含了node2的一个副本,当你将node3添加到原来的node2上时,节点1中包含的副本并没有改变。
猜你喜欢
  • 1970-01-01
  • 2017-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-03
  • 2020-05-02
  • 2020-11-09
相关资源
最近更新 更多