+1  A: 

Sounds like you are asking for a Breadth-first search.

I think your question may be related to a homework assignment, so I won't divulge more details here.

lothar
Heh, it's not a homework assignment, I'm a little too old for school.
Terence Simpson
My apology, it just looked like one ;-)
lothar
+4  A: 

Use a breadth-first search. As you access a node that isn't equal to the query value, you push that node onto the back of the queue. Process nodes from the front of the queue first. The first match you find will be the one closest to the root.

Class* Class::findItem(const std::string& n) const {
    std::list<Class>::const_iteratior i;
    std::queue<Class*> q;
    q.push(this);
    while (!q.empty()) {
        Class *c = q.front(); q.pop();
        if (c->name() == n) return c;
        for(i=c->_members.begin(); i!=c->_members.end(); ++i)
            q.push(i);
    }
    return NULL;
}
marcog
Thanks, just want I'm looking for. And that code makes it simple to understand.
Terence Simpson
Just to note, std::queue had .front() not .top()
Terence Simpson
replaced top() with front() and added std:: to queue.
aib
+2  A: 

If you do it breadth-first-search style, i.e. first look at all the Bs, then all the Cs, etc., your match node will automatically be the closest.

chaos
+1  A: 

It seems as if you are interested in performing a BFS (Breadth Search First). The simplest way of implementing it is not by recursion but rather with a FIFO queue where you add the neighbor elements to the one you are testing at the end, and extract the first element from the queue to perform the next check.

The order of insertions would be [ A(1), B(2), B(3), C(3), ... ] and you will find B(3) before testing C(3).

David Rodríguez - dribeas