Binary search tree inorder traversal help

Hello, i am having trouble figuring out inorder traversal in this assignment.
I was given this function definition in the homework i have to declare it.
The problem i am having is how to use pointer to function to traverse the list.

1
2
3
4
5
6
7
void    CBSTree<NodeType>::InOrderTraversal(void  (*fPtr)(const NodeType&)) const;
void    CBSTree<NodeType>::InOrder(const CTreeNode<NodeType> *const nodePtr
                                          ,void (*fPtr)(const NodeType&)) const;
//nodePtr is a pointer to a NodeType object (this is a recursive function, initially this points to the root).
//fPtr is a pointer to a non-member function that takes a const reference to a NodeType object as input, and
//returns nothing


I know without the pointer to function parameter it will be like this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void InOrder(CTreeNode *nodePtr)
{
     if(nodePtr != NULL)
      {
         InOrder(nodePtr->left);
         cout<<nodePtr->value;
         InOrder(nodePtr->right);
      }

}
void InOrderTraversal()
{
InOrder(root);
}


I just don't know how to traverse inorder with the function definition i am given.
In the example you give, you do in-order traversal and you print out the node's value at the appropriate time. What you need to do is call the fPtr function instead:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void CBSTree<NodeType>::InOrderTraversal(void  (*fPtr)(const NodeType&)) const
{
    InOrder(root, fPtr);
}

void CBSTree<NodeType>::InOrder(const CTreeNode<NodeType> *const nodePtr,
                                          void (*fPtr)(const NodeType&)) const
{
    if (nodePtr) {
        InOrder(nodePtr->left);
        fPtr(nodePtr->value);   // call the function
        InOrder(nodePtr->left);
    }
}
when calling InOrder recursively should it be like this, since it has two parameters?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void    CBSTree<NodeType>::InOrder(const CTreeNode<NodeType> *const nodePtr
                                        , void (*fPtr)(const NodeType&)) const
{

    if(nodePtr != NULL)
    {
        InOrder(nodePtr->m_left,fPtr); // recursive call to left
        fPtr(nodePtr->m_value);
        InOrder(nodePtr->m_right,fPtr); // recursive call to right


    }
}
Yes, two parameters. Sorry for my error.
Topic archived. No new replies allowed.