Home >Backend Development >Golang >How Can You Efficiently Convert a List of Path Strings into a Tree-like Structure?
Creating a Treelike Structure from Path Strings
Converting an array of string paths into a tree-like structure can be challenging, especially when dealing with recursive data. Here's an efficient solution to the problem:
The given path array consists of strings representing the path to nodes in a tree. The desired output is a hierarchical tree structure with nodes and their children.
First, let's examine the provided code:
<code class="go">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 } }</code>
This code attempts to recursively create the tree, nhưng it has some issues:
To address these issues, here's a revised code sample:
<code class="go">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 }</code>
This code operates on a list of nodes, rather than the children of a single node. It checks if a node already exists before inserting it and creates new nodes instead of reusing the input node. Additionally, it handles the case where the given path doesn't start at the same root node by appending to the list of root nodes if necessary.
Example output:
[{ "name": "a", "children": [{ "name": "b", "children": [{ "name": "c" }, { "name": "g" }] }, { "name": "d" }] }]
This improved solution provides an efficient and accurate conversion from path strings to a hierarchical tree structure.
The above is the detailed content of How Can You Efficiently Convert a List of Path Strings into a Tree-like Structure?. For more information, please follow other related articles on the PHP Chinese website!