Reputation: 3935
Hello suppose you have ordinary unix path tree as input (as string).
root 0
root/file1.txt 1
root/file2.txt 2
root/folder1 3
root/folder1/file3.txt 4
root/folder1/file4.txt 5
e.t.c.
What is the better way to convert this string to tree data structure?
Upvotes: 2
Views: 2001
Reputation: 3935
Now i use simple tree representation, created by myself
template<typename T>
class TreeNode
{
public:
TreeNode() {};
TreeNode(T)
{
value = T;
}
TreeNode(const T& value)
: Value(value)
{
}
T Value;
vector<TreeNode<T>*> Children;
};
I don't really understand Gir's algorithm (posted above). But i suppose the solution must be the following:
1. Get a root node, set depth_level = 0
3. set support_node = root_node
4. for each path line
5. determine the quantity of slashes "/", key and file(folder) name
so for example in string root/folder1/file4.txt 5, num of slashes = 2 filename = file4.txt, key = 5
create current_node
6. if num_of_slashes == level + 2
7. set support_node = current_node
8. if num_of_slashes == level + 1
9. add children to support_node
10. And after that we must remember all ancestors, going down to leaves. Cuz we can return to any ancestor.
For me this algorithm seems to be really complicated. I don't understand algorithm, posted above, maybe it is possible to clarify this question? Maybe the structure i use to store the tree isn't the best one?
Upvotes: 1
Reputation: 849
something like this:
create a root node for '\'
node=root;
token=getNextToken(inputString);
while (token){
if (!node.childExist(token)) node.createChild(token)
node=node.Child(token)
token=getNextToken(inputString);
}
Upvotes: 1