-1

I have a function to which I am passing a node tree. The function is supposed to print the node tree in this form:

root
 node
  node
  node
 node
 node
  node
   node
 node

I cant seem to wrap my head around how to do it. This is what I got so far:

void IterateTree(Node &rNode )
{
    printf("\t\n");
    std::cout << rNode.Name() << std::endl;

    int i = 0;
    for (std::list<Node>::iterator it = rNode.childs.begin(); it != rNode.childs.end(); ++it)
    {
        printf("%d: ", i);
        IterateTree(*it);
        printf("\b");
        i++;
    }
}

My Question is: is there a standard way of iterating and printing a node tree with the correct indentation?

tzippy
  • 6,458
  • 30
  • 82
  • 151

2 Answers2

1

Use another parameter to track the 'depth' of recursion

void IterateTree(Node &rNode , int depth)
{
    printf("\t\n");
    std::cout << rNode.Name() << std::endl;

    int i = 0;
    for (std::list<Node>::iterator it = rNode.childs.begin(); it != rNode.childs.end(); ++it)
    {
        for(int j=0; j<depth; j++){printf(" ");}
        printf("%d: ", i);
        IterateTree(*it, depth+1);
        printf("\b");
        i++;
    }
}

My Answer Is: few people print trees, especially not in plain text, so there is no standard for indentation.

0

Haven't tested it but my first guess would be sth. like this:

void iterateTree(Node &node, int level = 0){
    for(int i = 0; i < level; i++) printf("\t"); //foreach level print a tab

    cout << rNode.Name() << endl; //output the node

    int i = 0;
    level += 1; //if the for runs there is a next level
    for(list<Node>::iterator it = r.Node.childs.begin(); it != rNode.childs.end(); ++it){
        iterateTree(it, level);
    }
} 
Jan Raufelder
  • 287
  • 7
  • 23