// 面试题68:树中两个结点的最低公共祖先
// 题目:输入两个树结点,求它们的最低公共祖先。
const std::shared_ptr<node_tree<int>> last_comm_parent(
const std::shared_ptr<node_tree<int>>& root,
const std::shared_ptr<node_tree<int>>& node1,
const std::shared_ptr<node_tree<int>>& node2)
{
if(root == nullptr || node1 == nullptr || node2 == nullptr)
return nullptr;
std::list<const std::shared_ptr<node_tree<int>>> path1;
_path(root, node1, path1);
std::list<const std::shared_ptr<node_tree<int>>> path2;
_path(root, node2, path2);
auto it1 = path1.begin();
auto it2 = path2.begin();
std::shared_ptr<node_tree<int>> last = nullptr;
while(it1 != path1.end() && it2 != path2.end())
{
if(*it1 == *it2)
last = *it1;
it1++;
it2++;
}
return last;
}
bool _path(const std::shared_ptr<node_tree<int>>& root,
const std::shared_ptr<node_tree<int>>& node,
std::list<const std::shared_ptr<node_tree<int>>>& path)
{
path.push_back(root);
if(root == node)
return true;
bool found = false;
auto i = root->childs.begin();
while(!found && i < root->childs.end())
{
found = _path(*i, node, path);
++i;
}
if(!found)
path.pop_back();
return found;
}