Doug
Doug

Reputation: 1316

C++ Recursive Traversals with Function Pointers

template <class T>
void BT<T>::inOrder(void (*inOrderPtr)(T&))
 {
     inOrderPtr(inOrder(this->root));
 }
template <class T>
void BT<T>::inOrder(Node<T>* root) const
 {
    if (root->left != NULL)
       inOrder(root->left);
       //something here
    if (root->right != NULL)
       inOrder(root->right);
 }

Ok I am trying to create this Traversal via recursion. I actually posted this problem before but I was going about it wrong due to me having to use a function pointer. I don't understand what I'm suppose to do. I've got the public wrapper that calls on the private one... but the public one is the one with the function being passed in so what do I even do with it?? I feel retarded so even if someone were to give me a small hint I'm sure I'd get it. I just don't know where to go from here.

an example of a code that calls on it is this:

first.inOrder(print_val)

Upvotes: 1

Views: 1958

Answers (1)

Jim Buck
Jim Buck

Reputation: 20726

This is how to do it properly, but Node::GetItem needs implementing in order for this to be 100% correct:

template <class T>
T& Node<T>::GetItem() const
 {
    // TODO - implement getting a T& from a Node<T>
    return m_item; // possible implementation depending on Node's definition
 }

template <class T>
void BT<T>::inOrder(void (*inOrderPtr)(T&))
 {
    inOrder(this->root, inOrderPtr);
 }

template <class T>
void BT<T>::inOrder(Node<T>* root, void (*inOrderPtr)(T&)) const
 {
    if (root->left != NULL)
       inOrder(root->left, inOrderPtr);

    inOrderPtr(root->GetItem());

    if (root->right != NULL)
       inOrder(root->right, inOrderPtr);
 }

Upvotes: 4

Related Questions