// 找到根节点到目标节点的一条路径,如果存在的话,保存到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;
}
本文介绍了一种算法,用于查找二叉树中两个指定节点的最后一个共同父节点。该算法首先寻找从根节点到目标节点的路径,然后比较这两条路径以找到最后的公共父节点。
2492

被折叠的 条评论
为什么被折叠?



