2017-07-25 27 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