【问题标题】:Path tree to tree structure路径树到树结构
【发布时间】:2012-08-10 22:19:21
【问题描述】:

您好,假设您有普通的 unix 路径树作为输入(作为字符串)。

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.

将这个字符串转换为树数据结构的更好方法是什么?

【问题讨论】:

  • 问:什么意思?另外:看这里:stackoverflow.com/questions/205945/…
  • 我有路径树作为字符串。我需要制作树数据结构(c++ 类)并反映适当的层次结构。
  • 我认为没有最好的方法。你只需要定义你的树结构并解析你的文件。换句话说,这是正常的编程工作,没有技巧。
  • 没有“更好”的方法。如果你想要一个像树这样的文件系统,你需要一个像虚拟文件系统这样的东西。或者您可以编写一个立即添加完整路径的函数。您应该首先使用 std::map。

标签: c++ algorithm tree


【解决方案1】:

类似这样的:

为'\'创建一个根节点

node=root;
token=getNextToken(inputString);
while (token){
 if (!node.childExist(token)) node.createChild(token)
 node=node.Child(token)
 token=getNextToken(inputString);
}

【讨论】:

  • 是的 - 这绝对是解析字符串以构建树的好算法。下一个问题是“我用什么来实现树?”这就是我上面引用的链接所在:stackoverflow.com/questions/205945/…。正如 jahhaj 所说,没有任何一种开箱即用的内置“最佳方式”。
  • Gir:不允许使用任何第三方库。您的代码中的节点是什么?我
  • paulsm4:我看到了这个链接,但我不能使用 boost 图形库来解决这个问题
  • 你不需要任何第三方库——你可以自己写一个树类
【解决方案2】:

现在我使用我自己创建的简单树表示

template<typename T>
class TreeNode
{
public:
    TreeNode() {};

    TreeNode(T)
    {
        value = T;
    }

    TreeNode(const T& value)
        : Value(value)
    {
    }

    T Value;
    vector<TreeNode<T>*> Children;
};

我不太了解 Gir 的算法(已在上面发布)。但我想解决方案必须如下:

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.

对我来说,这个算法似乎真的很复杂。我不明白上面发布的算法,也许可以澄清这个问题?也许我用来存储树的结构不是最好的?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多