我已经卡了两天了,因为我不太熟悉指针和递归。我有一个路径结构的数组,比如:
s:=[]string {
"a/b/c",
"a/b/g",
"a/d",
}
使用这样的数据结构:
type Node struct {
Name string `json:"name"`
Children []Node `json:"children"`
}
我希望最终的结果是这样的:
{
"name": "a",
"children": [
{
"name": "b",
"children": [
{
"name": "c",
"children": []
},
{
"name": "g",
"children": []
}
]
},
{
"name": "d",
"children": []
}
]
}
我尝试使用递归来构建它,对于一个字符串(例如:“a/b/c”)它可以工作得相当好。但是,一旦我尝试实现一些应该添加缺失节点(“a/b/g”中的“g”)到树中的东西时,我就卡住了。
我有类似以下的代码:
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
}
}
有人能给我指出一个高效的解决方案吗?