0

I am looking at various implementations of AVL trees in particular a function to traverse the tree. I have come across different methods to achieve this however there is this one that i do not understand.

template <class TYPE, class KTYPE>
void  AvlTree<TYPE, KTYPE> 
  ::  AVL_Traverse (void (*process)(TYPE dataProc))
{
//  Statements 
    _traversal (process, tree);
    return;
}   // end AVL_Traverse 

/*  ===================== _traversal ===================== 
    Traverse tree using inorder traversal. To process a
    node, we use the function passed when traversal is called.
       Pre   tree has been created (may be null) 
       Post  all nodes processed 
*/

template <class TYPE, class KTYPE>
void  AvlTree<TYPE, KTYPE> 
  ::  _traversal (void(*process)(TYPE dataproc),
                  NODE<TYPE> *root)
{
//  Statements 
    if (root)
       {
        _traversal  (process, root->left);
        process     (root->data);
        _traversal  (process, root->right);
       } //  if 
    return;
}   //  _traversal 

in particular, in the above code could someone help me understand what this means and what it is doing

AVL_Traverse (void (*process)(TYPE dataProc))

i do not understand what this part means

AVL_Traverse (void (*process)

what is the pointer process used for?

william_
  • 1,131
  • 6
  • 20
  • The parameter is `void (*process)(TYPE dataProc)`, which is a function pointer. As the comment says, "To process a node, we use the function passed when traversal is called." – molbdnilo May 04 '20 at 06:30
  • That's the syntax that you can use to receive a function pointer. In this case the function can take a type as a input, TYPE, and returns nothing (void). The _traversal method names this function "process" within its scope. In general your question has nothing to do with AVL trees but instead you're trying to understand some specific c++ syntax that you're encountered, so your title should be something like "what is this c++ syntax for/ what does it do?". – Elliott May 04 '20 at 06:32
  • i have changed my question title so are you saying that process is a pointer to the traversal function that takes one argument (dataProc)? if so what is the point of doing this? – william_ May 04 '20 at 06:37
  • 2
    The point is that the caller of the traversal function can decide what to do with the nodes' values - collect them, print them, or whatever - so you don't need to write a new traversal function every time you want to process the tree's data. – molbdnilo May 04 '20 at 07:08
  • See also https://stackoverflow.com/questions/14114749/c-function-pointer-syntax – Caleth May 04 '20 at 08:46

0 Answers0