I have a function that’s traversing an AVL tree in level-order. The output format is:
level 0: jim(2)
level 1: bob(1) joe(1)
But when I get to level 4 and up, I want to break it down so it will only show 8 items per line. So the out put would start to look like this:
level 4: item1(1) item2(1) item3(2) item4(2) item5(1) item6(2) item7(1) item8(2)
level 4: item9(2) item10(2)
Right now my code will display all the items, but only on one line. I’m having trouble figuring out how to improve this code so that it is formatted the way I want. How can I implement this?
Here are the current functions:
//PRINT BY LEVEL ORDER TRAVERSAL
void Avltree::level_order(Avlnode* root, ofstream &out){
int h = height(root);
for(int i = 0; i < h; i++){
out << "Level " << i << ": ";
print_level(root, i, out);
out << endl;
}
}
//PRINT A GIVEN LEVEL ON A TREE
void Avltree::print_level(Avlnode* root, int level, ofstream &out){
if(root == NULL)
return;
if(level == 0){
out << root->data << "(" << height(root) << ") ";
}
else if (level > 0)
{
print_level(root->left, level-1, out);
print_level(root->right, level-1, out);
}
}
You should pass a count as a parameter to the recursive function and when count % 8 (or whatever you want the number per line to be) is 0, then start a new line.