假设每个节点都有一个指向其父节点的指针,那么只需从每个起始节点向后追溯树.最终,两条路径必须相交.测试交集可以像维护std::map节点地址一样简单.
UPDATE
当您更新问题以指定无向树时,上述内容无效.一个简单的方法就是从节点#1开始执行深度优先遍历,最终你会遇到节点#2.这是树的大小的O(n).假设一棵完全普通的树,我不确定会有更快的方法.
假设你有
struct Node
{
std::vector<Node *> children;
};
Run Code Online (Sandbox Code Playgroud)
那么可以做的就是从根开始遍历整个树,并在遍历过程中保持整个链。如果你找到例如node1,那么你保存当前链,如果你找到node2,那么你在代码中检查交集(未经测试):
bool findPath(std::vector<Node *>& current_path, // back() is node being visited
Node *n1, Node *n2, // interesting nodes
std::vector<Node *>& match, // if not empty back() is n1/n2
std::vector<Node *>& result) // where to store the result
{
if (current_path.back() == n1 || current_path.back() == n2)
{
// This is an interesting node...
if (match.size())
{
// Now is easy: current_path/match are paths from root to n1/n2
...
return true;
}
else
{
// This is the first interesting node found
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(); // *i
}
return false;
}
Run Code Online (Sandbox Code Playgroud)