Home >Backend Development >Golang >How can I convert a path string array into a tree-like structure?
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 <p><strong>Advantages of the Solution:</strong></p> <ul> <li> <strong>Reusability:</strong> The function can be repeatedly applied to add multiple path strings to the tree.</li> <li> <strong>Integrity:</strong> It avoids duplicate nodes in the tree by checking for existing nodes before adding.</li> <li> <strong>Efficiency:</strong> Recursion ensures that the function only operates on necessary nodes in the tree.</li> </ul> <p><strong>Example Output:</strong></p> <p>The code generates the following output:</p> <pre class="brush:php;toolbar:false">[{ "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!