Implementing a tree in C++

Here is a simple method of creating a hierarchical tree (n-ary with no special properties), using STL containers. It isn’t pre-built, but it is dead simple, and takes advantage of some STL properties. To create your own searching, you’d have to implement your own algorithms, but that should be fairly painless.

template<typename T>
class TreeNode
{
public:
    TreeNode()
    {
    }

    TreeNode(const T& value)
        : Value(value)
    {
    }

    T Value;
    std::list<TreeNode<T> > Children;
};

Leave a Comment