Search code examples
c++treelevels

Print general tree levels


Sorry for my bad english.

I need to print the levels of a general tree or n-ary tree.

The struct of the tree is:

struct GTnode{
    int data;
    nodeGT *fc; //first child
    nodeGT *nb; //next brother
}

The difficulty of the algorithm is when you have 2 different node in the same level and each one have a child.

Editing If I have this tree for example:

              1
     2        7        8
  3    6            9     12
 4 5              10 11

I have to print:

1
2 7 8
3 6 9 12
4 5 10 11

Each endl represents a different level in the tree

Editing An idea of my code is the next:

void printLevel(GTnode *root){
   GTnode *aux = root;
   if(root != NULL){
      cout<<aux->data;
      printLevel(aux->nb);
      cout<<end; //Print the space between levels
      printLevel(aux->fc);
   }
}

I know this is wrong but is just an idea of what I have.


Solution

  • You need to do a level-order/breadth-first traversal of the tree (wp). To do that you need a queue. Put the root in the queue. Then do this until the queue is empty: Take the first out, add its ->fc to the queue and go to its ->nb (go through all the ->nb's until there are nomore and each time you add its ->fc to the queue).