Tree

From ProjectFreedom

Jump to: navigation, search

Tree is a general purpose class for manipulating trees. It is a template class which has the key as the template parameter. Each node can have any number of children, the children are themselves a Tree. The key and children are protected, so Tree can be derived from while still allowing direct manipulation of the tree. PFreedom::BinaryTree is a binary tree implementation which has been derived from Tree.

Contents

General Use

Instantiation

Tree has two constructors, one takes no parameters and the other takes the number of children. Both create an empty tree and can have as many children added to them as needed. The second one allocates space for the number of children specified. This is particularly useful for derived classes like BinaryTree which need a fixed number of children.

Tree can be created with either:

Tree<Type> myTree;

or

Tree<Type> myTree(numChildren);

The key will be of type "Type". "Type" must be assignable, comparable for equality, and copy constructible. Pointers can be used, but since there is no way of knowing whether type is a pointer or not at runtime, the pointer cannot be dereferenced and compared for equality, so the find function may not work.

Functions

Only the functions which aren't self evident will be discussed here. If you need to know about the others you can look them up in the API reference.

forEachChild

forEachChild takes a function pointer and calls that function for each child in the tree. It is overloaded and can take either a member function or a non member function. The one that can take a member function is templated so that it can be called with any class. The prototypes are (for Tree<T>):

template <class MemberOf> void forEachChild(MemberOf *object, void (MemberOf::*callback)(Tree<T>*, void*), void *data);
void forEachChild(void (*callback)(Tree<T>*, void*), void *data);

The second one takes a pointer to the function to be called and a pointer to the data to pass to the function. The function will be passed a pointer to the current child node and the data. The function must be of type:

void (*callback)(Tree<T>*, void*);
Personal tools