1
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)

1 Answer 1

4

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);
 }
Sign up to request clarification or add additional context in comments.

4 Comments

Wait why do I need to get T&? I was told I would only need a Public Wrapper and a private recursive function for this. So I'm not exactly sure what the GetNodeType is suppose to do.
I think within the scope of the assignment that isn't needed. it actually "functions" now. I have to fix a few other things with other functions... but this actually worked out good. Thanks so much.
Let's say Node looks like template <class T> class Node { T item_; }; then GetNodeType's body would be "return node->item_;"
@Doug - Yeah, Adam's right. Since you have a Node<T> pointer, but the passed-in function needs a T&, you need to supply the code that gets a T from a Node<T>. It is mostly likely as simple as Adam's code snippet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.