2017-07-25 42 views
0

我有一个非常具体的问题,我找不出解决方案。转换地图到树中去

我有一个map[string]Metric,我想转换成一个树在前端使用。 Metric界面看起来有一个Path()Name()方法,name方法返回句点分隔的路径的最后一部分(所以'my.awesome.metric'的路径将表示这个度量的名称为'metric') 树应按路径排序,并应包含IndexNode s。这个结构是这样的:

type IndexNode struct { 
    Name string 
    Path string 
    Children []*IndexNode 
} 

所以地图是这样的:

{ 
    my.awesome.metric.downloads 
    my.awesome.othermetric.downloads 
    my.awesome.othermetric.uploads 
    my.other.cool.metric 
} 

应该导致这样的树:(抱歉粗ASCII艺术)

 +-- other -- cool -- metric 
    | 
my --+    +-- metric -- downloads 
    |    | 
    +-- awesome --+     +-- downloads 
        |     | 
        +-- othermetric --+ 
            | 
            +-- uploads 

注我只有一个根节点(我在这种情况下)。树内的顺序对我无关紧要。

我尽力而为,想不出来......经过大量的googleing(只显示我如何创建二叉搜索树和GoDS库),我辞职并决定在这里问我第一个问题

感谢您的帮助!

回答

0

更改Childrenmap[string]*IndexNode你已经到了一半。如果你不介意看起来很慢,你可以使用切片,但这意味着你需要在每次遍历树时搜索切片以找到你想要的子。在这种情况下,地图更快,更容易。

现在你只需要编写一个递归函数来递减树,使路径中每个元素都需要节点,直到到达结尾。

不幸的是我没有一个例子随时访问,我的代码在我的其他电脑:(

一个快速和肮脏的例子上:

type Tree struct { 
    Parent *Tree 
    Children map[string]*Tree 
    Payload bool // Your data here 
} 

func NewTree(parent *Tree, path []string, payload bool) *Tree { 
    if parent == nil { 
     parent = &Tree{nil, map[string]*Tree{}, false} 
    } 
    if len(path) == 0 { 
     parent.Payload = payload 
     return parent 
    } 

    child := parent.Children[path[0]] 
    if child == nil { 
     child = &Tree{parent, map[string]*Tree{}, false} 
     parent.Children[path[0]] = child 
    } 
    return NewTree(child, path[1:], payload) 
} 

用法:

root := NewTree(nil, nil, false) 
newnode := NewTree(root, []string{"A", "B", "C"}, true) 

Try it on the Go Playground!

+0

这已经是一个很好的起点,但是使用以下代码:'root:= NewTree(nil,nil,false); NewTree ,[] string {“jooy”,“bluwhale”,“files”},true); NewTree(root,[] string {“jooy”,“bluwhale”,“users”},true); NewTree(root, ] string {“jooy”,“dexter”,“registrations”},true)',结果如下(错误)JSON:'{“children”:{“jooy”:{“children”:{“dexter”: {“children”:{“registrations”:{“children”:{},“data”:true}},“data”:false}},“data”:false}},“data”:false}' –

+0

哎呀!试图在平板电脑上输入代码不利于获得好的结果!我无法相信我做了一件愚蠢的事!我现在就解决它。谢谢你指出! –

0

下面是一个使用地图解决方案,穿越它可以帮助你populat e数据结构。可以在树形导航中创建它表示“Parent xxx Child xxx”的节点https://play.golang.org/p/sVqBCVgiBG