您的位置:首页 > 其它

求二叉树中两个节点的最低公共祖先

2015-08-29 17:27 357 查看
// 找到根节点到目标节点的一条路径,如果存在的话,保存到path中

bool GetNodePath(BinaryTreeNode *pRoot, BinaryTreeNode *pNode, list<BinaryTreeNode *> &path)
{
if (pRoot == pNode) {
path.push_back(pRoot);
return true;
}
if (pRoot == NULL)
return false;
path.push_back(pRoot);
bool found = false;
found = GetNodePath(pRoot->lchild, pNode, path);
if (!found)
found = GetNodePath(pRoot->rchild, pNode, path);
if (!found)
path.pop_back();
return found;
}


// 主方法

BinaryTreeNode * GetLastCommonParent(BinaryTreeNode *pRoot, BinaryTreeNode *pNode1, BinaryTreeNode *pNode2)
{
if (pRoot == NULL || pNode1 == NULL || pNode2 == NULL)
return NULL;
list<BinaryTreeNode *> path1;
bool bResult1 = GetNodePath(pRoot, pNode1, path1);
if (!bResult1)
return NULL;
list<BinaryTreeNode *> path2;
bool bResult2 = GetNodePath(pRoot, pNode2, path2);
if (!bResult2)
return NULL;
BinaryTreeNode *pLast = NULL;
list<BinaryTreeNode *>::const_iterator iter1 = path1.begin();
list<BinaryTreeNode *>::const_iterator iter2 = path2.begin();

while (iter1 != path1.end() && iter2 != path2.end()) {
if (*iter1 == *iter2)
pLast = *iter1;
else
break;
++iter1;
++iter2;
}
return pLast;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: