I was looking at the question being asked here, but found only answers regarding binary trees.
I want to print in level order a tree that has 0 – n children.
I know the number of children, but my code isn’t working
The algorithm I thought is:
- print root
- print all of the children data
- for each child
- print the data
but the problem is that I don’t know where to stop, and when I try recursively, I fail.
This is the function that I wrote:
void printBFS(myStruct s)
{
int i = 0;
printAllChildrenData(s);
for (i = 0; i < s->number_of_children; i++)
{
myStruct childCurr = getChildAtIndex(s, i);
printBFS(chilCurr);
}
}
I’m messing here something.
I hope the functions are clear:
the printAllChildrenData prints all the data of all the children of S; it goes over the children list and prints it.
Editing
If I have this tree for example:
1
2 7 8
3 6 9 12
4 5 10 11
it should print:
1 2 7 8 3 6 4 5 9 12 10 11
instead of:
1 2 7 8 3 6 9 12 4 5 10 11
This code, which is closely based on your code (but expanded into a SSCCE), produces the output:
The code uses the designated initializer feature of C99 (one of the most useful additions to C99, IMNSHO). I’ve chosen to use a ‘better’ name than
myStructfor the structure; it represents a tree, so that’s what it is called. I’ve also not hidden the pointer in the typedef, and made the printing code const-correct (printing code should not normally modify the data structure it is operating on). It also uses the C99 option to declare a variable in the first clause of aforloop. I introduced an extra function,printTree(), which prints the data from the root node, calls yourprintBFS()to print the body of the tree, and prints a newline to mark the end of the output; theprintTree()function is called to print a tree. Note the systematic use ofprintData()to print the data for a node. If the data was more complex than a single integer, this would allow you to write the printing code once.Careful study of the code will show that the
printBFS()below is isomorphic with what you show, which in turn suggests that your problem is not in the code you show. That means it is probably in the code you use to build the tree, rather than in the code used to print it. Since you’ve not shown us the tree-building code, it makes it hard for us to predict what the problem is.You can easily revise the testing to print each node in turn: