So Basically I want to only print the first 5 node of a AVL tree using recursion
void printInOrder(void* theTree, void(*printnode)(void *data)) {
struct AVLTreeNode *node= (struct AVLTreeNode*)theTree;
if (node == NULL) return;
printInOrder(node->left, printnode);
(printnode)(node->data);
printInOrder(node->right, printnode);
}
the code above is a recursive inorder print i would just like to modify it to only print out the first 5 nodes of the tree. Also here is the printnode function
void printnode(void *node){
struct todo *printnode = node;
printf("%s, %d\n", printnode->activity, printnode->priority);
}
You have to tell the function when to stop: you can supply a counter of how many nodes are still available to print (initially 5), and each time one node is actually printed, you decrement the counter.
(Or you can increment the counter, but in that case the check has two terms – current counter value and maximum counter value – and you need to pass both as parameters, or make them global variables).
If you need to do something in addition to print, or need a more flexible
If you need to do something in addition to print, or need a more flexible function, you can do the same but passing the parameters to
printnode:In this second case, it is
printnodethat manipulates the counter, whileprintInOrderjust passes it along. Now,printnodegets called once for each node, but does the actual printing only when counter is nonzero, and can do any other housekeeping in all cases.