Sequential numbering by recursive function? e.g. 2, 2.1, 2.1.1, 2.2, 2.2.1

I have a recursive function that reads the "table of contents" of documents from a database. I would like to print the numbering with a document that reflects where the element is in the tree, for example.

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,

and etc.

Rather stupid about it at the moment - please help?

+3
source share
3 answers

Just include the "path" argument in the function and add to it when you go. Pseudo Code:

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])
  }
}
0
source

It would be helpful to see your code. Assuming that the data is stored in some hierarchical representation, the recursion structure may look like this:

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);
  }
}

, . .

+5

? SQL Server 2005 , "" ( ), CTE. ( XML- SQL Server.)

, . . , .

0

Source: https://habr.com/ru/post/1741780/


All Articles