I have to code up a function for a lab in a binary search tree for in order traversal. My problem is I've been given an interface that I have to follow and in it the only parameter I can pass to the traversal function is another function of void return type:
void BinarySearchTree<ItemType, KeyType>::inorderTraverse(void visit(ItemType&)) const
The visit function is basically a function that I would define for a specific use case for the tree, like say I want to print out the tree in ascending order in which case the function I would pass to the inorderTraverse function would be a print function. I can't figure out how to traverse the entire tree without having a node pointer as a parameter. I'm not asking for the entire code, just advice that can point me in the right direction! Here's the BinarySearchTree.h:
template<typename ItemType, typename KeyType>
class BinarySearchTree
{
private:
BinaryNode<ItemType>* rootPtr;
// Recursively deletes all nodes from the tree.
void destroyTree(BinaryNode<ItemType>* subTreePtr);
// Recursively finds where the given node should be placed and
// inserts it in a leaf at that point.
BinaryNode<ItemType>* insertInorder(BinaryNode<ItemType>* subTreePtr,
BinaryNode<ItemType>* newNode);
// Returns a pointer to the node containing the given value,
// or nullptr if not found.
BinaryNode<ItemType>* findNode(BinaryNode<ItemType>* treePtr,
const KeyType& target) const;
public:
//------------------------------------------------------------
// Constructor and Destructor Section.
//------------------------------------------------------------
BinarySearchTree();
virtual ~BinarySearchTree();
//------------------------------------------------------------
// Public Methods Section.
//------------------------------------------------------------
bool add(const ItemType& newEntry);
ItemType getEntry(const KeyType& aKey) const throw(NotFoundException);
bool contains(const KeyType& aKey) const;
//------------------------------------------------------------
// Public Traversals Section.
//------------------------------------------------------------
void inorderTraverse(void visit(ItemType&)) const;
}; // end BinarySearchTree
#include "BinarySearchTree.cpp"
#endif
void BinarySearchTree<ItemType, KeyType>::inorderTraverse(...) constis a method of theBinarySearchTree-as such, you do have access to the root node of the tree inside the mehod. Your visitor won'y receive the node itself, but the visitor does not need to traverse the tree: it is theinorderTraversethat should do it.