How to output height of each node in BST?
Jul 9, 2011 at 2:41am UTC
I'm trying to output the height or level of each node in a binary search tree. I've tried a lot of algorithms but I had to scrap them. I'd like to be able to put it right in my traversal functions using a counter:
void preorder(treenode_type *r)
{
if (r != nil)
{
cout << (*r).info;
preorder((*r).left);
preorder((*r).right);
}
}
without having to make a separate function. Can anyone point me in the right direction?
Jul 9, 2011 at 3:16am UTC
Well, if adding a parameter to your traversal function won't mess with your requirements:
1 2 3 4 5 6 7 8 9 10
void preorder(treenode_type *r, int level)
{
if (r != nil)
{
cout << (*r).info;
cout << endl << "Level: " << level;
preorder((*r).left, level + 1);
preorder((*r).right, level + 1);
}
}
1 2
treenode_type* root = bst->root();
preorder(root, 0);
Last edited on Jul 9, 2011 at 3:18am UTC
Topic archived. No new replies allowed.