Introduction:
Constructing a tree-like structure from an array of path strings can be challenging, but with the appropriate techniques, it can be efficiently achieved.
Solution:
The provided solution employs a recursive function, AddToTree, which takes as input a list of nodes representing the current state of the tree and the remaining path segments to be added. The algorithm proceeds as follows:
Code Snippet:
<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>
Advantages of the Solution:
Example Output:
The code generates the following output:
[{ "name": "a", "children": [{ "name": "b", "children": [{ "name": "c" }, { "name": "g" }] }, { "name": "d" }] }]
The above is the detailed content of How can I convert a path string array into a tree-like structure?. For more information, please follow other related articles on the PHP Chinese website!