Get tree structure from path string

I am stuck from 2 days since I am not sure about pointers and recursion. I have an array of paths such as structures, say:

s:=[]string {
  "a/b/c",
  "a/b/g",
  "a/d",
}

With a data structure like this:

 type Node struct {
   Name     string `json:"name"`
   Children []Node `json:"children"`
}

I would like to get something like this:

{
 "name": "a",
 "children": [
     {
      "name": "b",
      "children": [
        {
         "name": "c",
         "children": []
        },
        {
         "name": "g",
         "children": []
        }
      ]
    },
    {
     "name": "d",
     "children": []
    }
  ]
}

I tried to create it with recursion, which works fine, but only for one line (for example, "a / b / c"), as soon as I try to implement something that should add the missing nodes ("g" to "a / b / g ") to the tree I'm stuck with.

I had something like:

func appendChild(root Node, children []string) Node {
   if len(children) == 1 {
      return Node{children[0], nil}
   } else {
      t := root
      t.Name=children[0]
      t.Children = append(t.Children, appendChild(root, children[1:]))
      return t
   }
}

Can someone point me to an effective solution?

+4
source share
1 answer

https://play.golang.org/p/9pER5cwChF

func AddToTree(root []Node, names []string) []Node {
    if len(names) > 0 {
        var i int
        for i = 0; i < len(root); i++ {
            if root[i].Name == names[0] { //already in tree
                break
            }
        }
        if i == len(root) {
            root = append(root, Node{Name: names[0]})
        }
        root[i].Children = AddToTree(root[i].Children, names[1:])
    }
    return root
}

( , omitempty children, null JSON):

[{
    "name": "a",
    "children": [{
        "name": "b",
        "children": [{
            "name": "c"
        }, {
            "name": "g"
        }]
    }, {
        "name": "d"
    }]
}]

:

  • , node. , , node (a), . - "" node .
  • node. . len (children) > 1, node, , . , . node.
  • . , , , ( , node b)
+1

Source: https://habr.com/ru/post/1676473/


All Articles