I know this is probably a simple question but it's been a while since I've done any C programming. I am trying to perform an inorder traversal on x nodes where x is some number I pass to the function. My inorder function is calling itself recursively and for the life of my I cannot figure how to stop the traversal after its visited x nodes. Here is my inorder traversal function:
void inorder(node h)
{
if (h != NULL)
{
inorder(h->l);
printf(" %d\n",h->item);
inorder(h->r);
}
return;
}
Any guidance is greatly appreciated.
Try this - should work for only x number of nodes visited (where the number of nodes visited are the nodes which are the candidates for being printed);
int inorder(node h, int x)
{
if (h != NULL && x > 0)
{
x = inorder(h->l, x);
if (x > 0) {
printf(" %d\n",h->item);
x--;
}
if (h->r && x > 0)
x = inorder(h->r, x);
}
return x;
}
[EDIT: This code was corrected by @nhahtdh after some discussion on the definition of nodes visited and decrementing the value of x. The working test code can be seen here.