While working on a small project, I tried to implement a super simple tree class in C++. It supports an arbitrary number of branches from each node.
In addition to general comments, my main concerns are:
- Are there other common tree functions that should be implemented? (So far I know about traversal and search, but I don't think I'll need them for my project.)
- Can this class leak memory?
- How can I write good unit tests?
Tree.h:
#ifndef Tree_h
#define Tree_h
#include<vector>
// Templated tree class
template <typename T>
class Tree {
public:
// Child nodes
std::vector<Tree<T> *> branches;
// Top datum
T leaf;
// Constructor from element
Tree<T>(const T & leaf_in) : leaf(leaf_in) { }
// Copy constructor (deep copy)
Tree<T>(const Tree<T> & tree_in) {
cloneTree(this, tree_in);
}
// Overloaded assignment operator
Tree<T> & operator=(const Tree<T> & tree_in) {
// Do nothing if called on itself
if (this == & tree_in) {
return * this;
}
// Delete this tree
chopTree();
// Copy the other tree in its place
cloneTree(this, tree_in);
return * this;
}
// Grow function
// Modifies heap
void grow(const T & leaf) {
Tree * branch = new Tree(leaf);
branches.push_back(branch);
}
// Destructor
~Tree<T>() {
chopTree();
}
private:
// Cleans up heap from grow function
// Recursively called on each branch
void chopTree() {
for (auto branch : branches) {
branch->chopTree();
delete branch;
branch = 0;
}
branches.clear();
}
// Copies all of another tree's items into this tree
// Requires that other != this
void cloneTree(Tree<T> * self, const Tree<T> & other) {
self->leaf = other.leaf;
// copy the leaves
for (auto branch : other.branches) {
self->grow(branch->leaf);
}
// copy the branches
for (int i = 0; i < self->branches.size(); ++i) {
cloneTree(self->branches.at(i), * other.branches.at(i));
}
}
};
#endif // Tree_h
Note: There are several other C++ Tree questions, but I didn't find the answers I was looking for. In case there is a duplicate question that I missed, let me know in the comments, and I'll delete the question.
chopTree
, now that's an interesting name :D \$\endgroup\$