I am implementing a tree structure in c++ with a node class like this:
class Node {
protected:
// relations
Node *_parent;
std::vector<Node*> _children;
public:
// some example method
void someMethod(Node *node) {
// do something with *node
for (int i = 0; i < node->_children; i++) {
_children[i]->myFunction;
}
}
}
Now, to work on the nodes in my tree I am implementing recursive functions like someMethod
in my example.
It works, but I end up writing the same recursion code over and over again for every new function that works on my tree.
Is there a generic way to iterate a tree structure like I would on a plain array? Some method that returns the next object, until I'm done with the whole branch.
EDIT:
Thanks to everybody who has commented so far, with your help I could narrow down the problem. From my understanding (I'm new to c++), I need an iterator class that encapsulates the code for traversing my tree.
Accessing all tree members should be as simple as that:
for (Node<Node*>::iterator it = _node.begin(); it != _node.end(); ++it) {
Node *node = *it;
// do something with *node
}
Now the question is:
How do I implement such an iterator?