Suppose you have
struct Node
{
std::vector<Node *> children;
};
what can be done is to cross the entire tree, starting from the root, keeping the entire chain during the traversal. If you find, for example, node1, then you save the current chain, if you find node2, then you check the intersection ... in the code ( UNTESTED ):
bool findPath(std::vector<Node *>& current_path,
Node *n1, Node *n2,
std::vector<Node *>& match,
std::vector<Node *>& result)
{
if (current_path.back() == n1 || current_path.back() == n2)
{
if (match.size())
{
...
return true;
}
else
{
match = current_path;
}
}
for (std::vector<Node *>::iterator i=current_path.back().children.begin(),
e=current_path.back().children.end();
i != e; ++i)
{
current_path.push_back(*i);
if (findPath(current_path, n1, n2, match, result))
return true;
current_path.pop_back();
}
return false;
}