Binary tree, print out which level I am on
I want to print out into my sorted tree on which level this number was and that must be a recursion function.
Here is my code:
void printout(KNOTEN *start) {
if (start == NULL)
return;
printout(start->left);
printf("%d\n", start->number);
printout(start->right);
free(start);
}
Here is an example of the output:
My input Numbers 41, 18467, 6334 , 26500, 19169
Outprint is 41,6334,18467,19169,26500
What I w开发者_如何学Goant is:
41 Level 1 , 6334 level 3 , 18467 level 2 , 26500 level 3 , 19169 level 4
I would modify it to this:
void printout(KNOTEN *start, int depth)
{
if(start == NULL)
return;
printout(start->left, depth+1);
printf("%d(%d) \n",start->number, depth);
printout(start->right, depth+1);
free(start);
}
here is a hint. your prototype is this
printout(KNOTEN *start, int the_level)
and this is how you call it to start your search.
printout(node, 1);
and there is a the_level + 1 in two places in your code.
good luck
This sounds like homework, so I'm not going to give you complete code. But the idea is to keep count of how many recursive calls you've made:
int myRecursiveFunction(Node *node, int thingToFind, int level)
{
if (someCondition())
{
return level;
}
else
{
if (goLeft())
{
return myRecursiveFunction(node->left, thingToFind, level+1);
}
else
{
return myRecursiveFunction(node->right, thingToFind, level+1);
}
}
}
...
int level = myRecursiveFunction(root, thingToFind, 0);
精彩评论