递归函数的连续编号?例如2,2.1,2.1.1,2.2,2.2.1

时间:2010-04-19 14:07:41

标签: c# recursion

我有一个递归函数,从数据库中读取文档的“目录”。 我想用反映项目在树中的位置的文档打印编号,例如

1. First item,
    1.1 Child of first item,
        1.1.1 Child of child of first item,
    1.2 Child of first item,
2. Second item,
    2.1 Child of second item,

此刻相当难过 - 请帮忙吗?

3 个答案:

答案 0 :(得分:5)

查看代码会很有用。假设数据存储在某种分层表示中,递归的结构可能如下所示:

void PrintTOC(string prefix, List<Sections> sections) {
  // Iterate over all sections at the current level (e.g. "2")
  for(int i = 0; i<sections.Length; i++) {
    // Get prefix for the current section (e.g. "2.1")
    string num = String.Format("{0}.{1}", prefix, i+1);
    // Write the current section title
    Console.WriteLine("{0} {1}", num, sections[i].Titles);

    // Recursively process all children, passing "2.1" as the prefix
    if (sections[i].Children != null)
      PrintTOC(num, sections[i].Children);
  }
}

这将保留前缀参数,该参数包含父节的索引。当前部分中的所有数字都附加在此前缀之后。

答案 1 :(得分:0)

只需在函数中包含一个“path”参数,然后随时添加它。伪代码:

function print_rec(String path, Node node) {
  print(path + node.title)
  for (int i=1; i<=node.children.length; i++) {
    print_rec(path+"."+i, node.children[i])
  }
}

答案 2 :(得分:0)

您的数据库平台是什么?如果您使用的是SQL Server 2005或更高版本,则可以使用单个CTE查询从“树”表(具有自引用键的表)获取此类路径。 (还有一些基于XML的技术可以在SQL Server中运行递归查询。)

否则,您将不得不像其他人所建议的那样在客户端代码中执行递归。在这种情况下,您可能需要考虑在开始递归和使用对象遍历结构之前选择所有相关数据。这样就可以避免对数据库进行大量的查询。

相关问题