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

最近公共父节点(即LCA问题)的一点思路

2012-10-12 19:36 344 查看
这个面试题可以说是众多面试官喜欢出的题目,自己写一下自己思路和代码,希望抛砖引玉,如果有错误请指正。

对于知道parent结点的部分,不做解析,值考虑已知root结点,lChild和rChild;

问题:找到二叉树中p1和p2的最近公共父节点。

//LCA问题
BTNode *FindNearestParentNode(BTNode *b, BTNode *p1, BTNode *p2)
{
if (NULL == b)
{
return NULL;
}
if(b == p1 || b == p2)
{
return b;
}
BTNode *lFind = FindNearestParentNode(b->lchild, p1, p2);
BTNode *rFind = FindNearestParentNode(b->rchild, p1, p2);
if(lFind && rFind)
return b;
return lFind ? lFind : rFind;
}


另外一种解法:就是把根节点到p1,p2的路径存储起来,然后比较。

bool FindNodePath(BTNode *b, BTNode *p, list<BTNode *> &path)
{
if (b == p)
{
return true;
}
path.push_back(b);
bool isFind = false;
if (b->lchild != NULL)
{
isFind = FindNodePath(b->lchild, p, path);
}
if(!isFind && b->rchild)
{
isFind = FindNodePath(b->rchild, p, path);
}
if(!isFind)
path.pop_back();
return isFind;
}

BTNode *NearParentNode(list<BTNode *>&path1,list<BTNode *>&path2)
{
BTNode *LCA;
list<BTNode *>::const_iterator i1 = path1.begin();
list<BTNode *>::const_iterator i2 = path2.begin();
for (i1;i1 != path1.end();i1++)
{
for (i2;i2 != path2.end();i2++)
{
if (*i1 == *i2)
{
LCA = *i1;
}
}
}
return LCA;
}

BTNode *NearestParentNode(BTNode *b, BTNode *p1, BTNode *p2)
{
if (b == NULL || p1 == NULL || p2 == NULL)
{
return NULL;
}
list<BTNode *> path1;
list<BTNode *> path2;
FindNodePath(b, p1, path1);
FindNodePath(b, p2, path2);
return NearParentNode(path1, path2);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息