次のようなものを試すことができます:
class Node
{
public:
// Other stuff.
const Node* getParent() const { return parent; }
private:
Node* parent;
std::vector<Node*> children;
};
const Node* getLowestCommonAncestor(const Node& lhs, const Node& rhs)
{
for (const Node* node1 = &lhs; node1 != nullptr; node1 = node1->getParent()) {
for (const Node* node2 = &rhs; node2 != nullptr; node2 = node2->getParent()) {
if (node1 == node2) {
return node1;
}
}
}
return nullptr;
}
または、親がいない場合:
namespace detail
{
struct LCAFlag {
enum { NoFound = 0, leftFound = 1, rightFound = 2 };
};
const Node* getLCA_Rec(const Node& root, const Node& lhs, const Node& rhs, unsigned int& flag)
{
if (&root == &lhs) {
flag |= LCAFlag::leftFound;
} else if (&root == &rhs) {
flag |= LCAFlag::rightFound;
}
if (flag == (LCAFlag::leftFound | LCAFlag::rightFound)) {
return nullptr; // both found. parent is the LCA
}
for (auto it = root.children.begin(); it != root.children.end(); ++it) {
const Node* res = getLCA_Rec(**it, lhs, rhs, flag);
if (res != nullptr) {
return res;
}
if (flag == (LCAFlag::leftFound | LCAFlag::rightFound)) {
return &root;
}
}
return nullptr;
}
}
const Node* getLCA(const Node& root, const Node& lhs, const Node& rhs)
{
unsigned int flag = detail::LCAFlag::NoFound;
return detail::getLCA_Rec(root, lhs, rhs, flag);
}