我有一个 url 列表,需要将其更改为 JSON 树结构。到目前为止,我已经尝试了几种不同的方法,但都失败了。目前我正在尝试将此算法转换为 Golang,但它没有做任何事情,我被困在他们的逻辑中,我到 golang 的转换是有缺陷的,我被困住了。
树.go
package tree
import (
"fmt"
)
type TreeNode struct {
Path string `json:"path"`
Children []TreeNode `json:"children"`
}
urls := []string{
"fenceprosc.com/hello-world/#respond",
"fenceprosc.com/199-2/12615753_1208442715850011_4650003168465028857_o/#respond",
"fenceprosc.com/199-2/28339_127294957298131_7361568_n/#main",
"fenceprosc.com/199-2/10917425_1025362007491417_2370903639534256456_n/#main",
"fenceprosc.com/199-2/vinyl-gate-2/#main",
"fenceprosc.com/199-2/vinyl-gate1/#main",
}
func GetTheParentNodeChildArray(path string, treeNodes *[]TreeNode) []TreeNode {
for _, treeNode := range *treeNodes {
if len(treeNode.Children) > 0 {
var possibleParent = false
for _, node := range treeNode.Children {
// What do I do here???
fmt.Println("node::", node)
}
if possibleParent {
return GetTheParentNodeChildArray(path, &treeNode.Children)
}
}
}
return *treeNodes
}
// Add an item node in the tree, at the right position
func addToTree(node TreeNode, treeNodes *[]TreeNode) {
parentNodeArr := GetTheParentNodeChildArray(node.Path, treeNodes)
fmt.Println("parentNodeArr", parentNodeArr)
if parentNodeArr == nil {
parentNodeArr = *treeNodes
}
parentNodeArr = append(parentNodeArr, TreeNode{
Path: node.Path,
})
}
//Create the item tree starting from urls
func createTree(nodes []TreeNode) []TreeNode {
var tree []TreeNode
for _, node := range nodes {
addToTree(node, &tree)
}
return tree
}
我也对任何其他解决方案完全开放,我对这个算法没有任何执着。只是很难弄清楚如何将它们构建成一棵树。
PIPIONE
相关分类