The easiest way (I think) is assigning a level for each node when creating it. Trivially the root node is at level 0. For all other nodes, level = parent.level + 1. You can do this easily when creating the tree. When you are searching for all the nodes at some level, you can make some kind of depth limited search. (similar to depth first search, except that your do not search after some level). The pseudocode is something like this:
PrintLimit(Node *node, int level)
{
if ( node->level == level )
print this node;
else if (node->level < level)
{
if (node->right != NULL)
PrintLimit(node->right, level);
if (node->left != NULL)
PrintLimit(node->left, level);
}
else if (node->level > level )
{
// do nothing, the code should not come here
}
}
Main Topics
Browse All Topics





by: SteHPosted on 2005-01-17 at 07:45:09ID: 13064136
Have you tried it with recursion? Call each node of parameter with level decremented. When level in a call is 0 print out the node.