I am working on a Binary Tree program for school and I have everything working perfectly. All I am working on now is the proper output. My teacher wants the output to be all the numbers in sorted order with commas after them.
My code that I have sorts the numbers perfectly and prints them, I am just not sure how to remove the comma after the last number.
Current Output: 1, 2, 3, 4,
Needs to be: 1, 2, 3, 4
Here is my code:
void BinaryTree::inorder(tree_node* p)
{
if(p != NULL)
{
if(p->left)
inorder(p->left);
cout << p->data << ", ";
if(p->right)
inorder(p->right);
}
else
return;
}
I have tried a few things to make it right but I just can’t figure it out.
Any help would be great.
Thanks.
One easy way is to print the separator character before the data, like this
This way we have changed your problem into skip printing the first comma. This is much easier. Hint: In order to keep track of whether to skip the comma you might need to introduce another argument to the function, since it is a recursive function.
As xmoex points out there is a more elegant way to print this tree resulting in very readable and logic code. Try to find this way for an extra challenge.
An unrelated hint: You can drop the return statement since its redundant – The function will return anyway! Like this:
This will yield less uneccessary code and will help you read your own code if you need to, for example, debug it quickly before a assignment due date.