Click to See Complete Forum and Search --> : Binary Tree Printing
KappuJ
December 5th, 2002, 10:43 PM
Hi,
I need to print a binary tree
1. in the order of its level ( root, left & right child, children of the left & right nodes, its children & so on )
1, 2, 3, 4, 5, 6,7,8 .... where 2 & 3 are the children of 1, 4 & 5 are the children of 2, 6 & 7 are the children of 3 & so on...
2. print them in the following manner
1
2
3
KappuJ
December 5th, 2002, 10:43 PM
Hi,
I need to print a binary tree
1. in the order of its level ( root, left & right child, children of the left & right nodes, its children & so on )
1, 2, 3, 4, 5, 6,7,8 .... where 2 & 3 are the children of 1, 4 & 5 are the children of 2, 6 & 7 are the children of 3 & so on...
2. print them in the following manner
1
2
4
5
....
3
the levels of the siblings should align.
How can I do these two ?
Any help with code samples would be greatly appreciated.
Thanks
- Kappu
TheCPUWizard
December 5th, 2002, 10:58 PM
Does the tree contain OBJECTS or Integers?
KappuJ
December 6th, 2002, 11:45 AM
The tree contains simple integers
cup
December 6th, 2002, 04:10 PM
You have a strange binary tree. Normally it is left, middle then right but you want it printed as middle, left right. Oh well - we all have our reasons. Assuming the structure is
struct bintree
{
struct bintree* left;
struct bintree* right;
int val;
};
Printing it is just
void printtree (struct bintree* node)
{
cout << node->val << endl;
if (node->left != 0) printree (node->left);
if (node->right != 0) printree (node->right);
}
or if you are likely to start with a null node then
void printtree (struct bintree* node)
{
if (node != 0)
{
cout << node->val << endl;
printtree (node->left);
printtree (node->right);
}
}
The latter looks neater but nests more deeply at runtime. If you wanted it as left, value, right, just move the printree of the left before the cout.
galathaea
December 6th, 2002, 04:40 PM
Are you trying to print them like
1
2
4
5
3
6
7
I was curious since you posted twice, and maybe weren't familiar as to how to get the tabbing to show up...
Yves M
December 7th, 2002, 12:45 AM
Originally posted by galathaea
I was curious since you posted twice
Sorry, no that was me. While writing the post he accidentally posted the half-done post and TheCPUWizard replied to that. I then merged the full question with this thread. But by deleting the first (uncomplete) post, I would delete the whole thread. Ok, I'm not trying to explain my life here, just that it's a technical glitch ;)
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.