PMG76
asked on
Binary tree output to screen
I'm trying to create a function that prints the binary tree out to the screen making each column start 4 spaces to the right of the precious column. Here is what I have so far. I seem to have something out of order though. Any thoughts ?
template <class ItemType>
void RTreeType<ItemType>::ScreenPrint (std::ostream& outFile, NodeType* tree, int spaces) const
{
if ( tree != NULL )
{
ScreenPrint(outFile,tree->right,spaces + 4);
for ( int x=1; x <= spaces; ++x)
cout << setw(4) << " ";
cout << tree->info << endl;
ScreenPrint(outFile,tree->left, spaces + 4);
}
}
It would help if you expanded a bit on what your actual problem is. Whilst it may very well be obvious to you it is not so obvious to others.
If I understand it correctly, you want to output the tree like this, correct ?
1
2 3
4 5 6 7
If so, that's quite hard to do with a recursive function.
1
2 3
4 5 6 7
If so, that's quite hard to do with a recursive function.
One approach would be to get the depth of the tree (to calculate the amount of spaces needed).
Then print one level of the tree at a time. The spaces at the beginning and between the values can be calculated based on the current level and the total depth of the tree.
Then print one level of the tree at a time. The spaces at the beginning and between the values can be calculated based on the current level and the total depth of the tree.
ASKER
yes that is what I need. I'm aware of the difficulty, but I have to use recursion. Right now my out put is like this:
999
500
123
2
So something is not working properly
999
500
123
2
So something is not working properly
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
If I understand the homework assingment well, one text line should display one node (tree rotated 90 degrees). If this is the case then the code is almost O.K. Only the for loop for generating the spaces can be simplified by using the variant of the std::string constructor that takes the counter and the character (remove the for loop completely.
By the way, your output can be fine if the root node contains 2, the right subtree has 999 in the top node, the left subtree is empty, etc.
By the way, your output can be fine if the root node contains 2, the right subtree has 999 in the top node, the left subtree is empty, etc.
cout << std::string(spaces, ' ') << tree->info << endl;
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.