您的位置:首页 > 职场人生

剑指offer——面试题50:树中两个结点的最低公共祖先

2016-12-15 14:48 459 查看
题目:求树中两个结点的最低公共祖先,此树不是二叉树,并且没有指向父节点的指针。

题目解析:

如下图一颗普通二叉树假设输入结点 F 和 H。



我们首先得到一条从根结点到树中某一结点的路径,这就要求在遍历的时候,有一个辅助内存来保存路径。比如我们用前序遍历的方法来得到从根结点到 H 的路径的过程是这样的:( 1 )遍历到 A,把 A 存放到路径中去,路径中只有一个结点 A;( 2 )遍历到 B,把 B 存到路径中去,此时路径为 A->B; ( 3 )遍历到 D,把 D 存放到路径中去,此,时路径为 A->B->D;( 4 ):遍历到 F,把 F 存放到路径中去,此时路径为 A->B->D->F;( 5) F 已经没有子结点了,因此这条路径不可能到这结点
H。 把 F 从路径中删除,变成 A->B->D; ( 6 )遍历 G。 和结点F 一样,这条路径也不能到达 H。边历完 G 之后,路径仍然是 A->B->D; ( 7 )由于 D 的所有子结点都遍历过了,不可能到这结点 H,因此 D 不在从 A 到 H 的路径中,把 D 从路径中删除,变成 A->B; ( 8 )遥历 E,把 E 加入到路径中,此时路径变成 A->B->E, ( 9 )遍历 H,已经到达目标给点, A->B->E 就是从根结点开始到达 H 必须经过的路径。

同样,我们也可以得到从根结点开始到达 F 必须经过的路径是 A->B。接着,我们求出这两个路径的最后公共结点,也就是 B。B 这个结点也是 F 和 H 的最低公共祖先.

为了得到从根结点开始到输入的两个结点的两条路径,需要追历两次树,每边历一次的时间复杂度是 O(n)。得到的两条路径的长度在最差情况时是 0(通常情况丁两条路径的长度是 O(logn)。

参考代码:

bool GetNodePath(TreeNode* pRoot, TreeNode* pNode, list<TreeNode*>& path)
{
if(pRoot == pNode)
return true;

path.push_back(pRoot);

bool found = false;

vector<TreeNode*>::iterator i = pRoot->m_vChildren.begin();
while(!found && i < pRoot->m_vChildren.end())
{
found = GetNodePath(*i, pNode, path);
++i;
}

if(!found)
path.pop_back();

return found;
}

TreeNode* GetLastCommonNode
(
const list<TreeNode*>& path1,
const list<TreeNode*>& path2
)
{
list<TreeNode*>::const_iterator iterator1 = path1.begin();
list<TreeNode*>::const_iterator iterator2 = path2.begin();

TreeNode* pLast = NULL;

while(iterator1 != path1.end() && iterator2 != path2.end())
{
if(*iterator1 == *iterator2)
pLast = *iterator1;

iterator1++;
iterator2++;
}

return pLast;
}

TreeNode* GetLastCommonParent(TreeNode* pRoot, TreeNode* pNode1, TreeNode* pNode2)
{
if(pRoot == NULL || pNode1 == NULL || pNode2 == NULL)
return NULL;

list<TreeNode*> path1;
GetNodePath(pRoot, pNode1, path1);

list<TreeNode*> path2;
GetNodePath(pRoot, pNode2, path2);

return GetLastCommonNode(path1, path2);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: