- Make a BFS
- Each node you take out of the
queue
you push_back into a vector
.
- Traverse the vector in reverse order.
Basically something like this:
queue<Node> q;
vector<Node> answer;
q.push(root);
while(!q.empty())
{
Node first = q.front();
answer.push_back(first);
q.pop();
for(every NODE reachable from first)
q.push(NODE);
}
reverse(begin(answer), end(answer));
This is just the algorithm, I've put the closest to code that I could. You can make your iterator logic using vector answer
now.
You could use a stack instead. The main point is: by traversing in a BFS you are doing the reverse sequence of what you are trying to achieve.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…