题目:给出两个结点A和B,求解这两个结点的最低公共祖先(LCA)
前提:为了更好的说明思路,这里让问题简单化,假设树是二叉树且树中只含有一个A和一个B。
举例:
条件(1)树为二叉搜索树
思路:
如果树为二叉搜索树且树中必须包含给出的两个元素,可以利用二叉搜索树的性质来做。
如果树中不包含给出的两个元素,输出的结果会是错误的。
代码:
struct BTNode
{
int m_nValue;
BTNode* m_pLeft;
BTNode* m_pRight;
};
BTNode* FindLCA(BTNode* pRoot,int nFirst,int nSec)
{
if (pRoot)
{
if (pRoot->m_nValue > nFirst && pRoot->m_nValue > nSec)
{
return FindLCA(pRoot->m_pLeft,nFirst,nSec);
}
else if (pRoot->m_nValue < nFirst && pRoot->m_nValue < nSec)
{
return FindLCA(pRoot->m_pRight,nFirst,nSec);
}
else
{
return pRoot;
}
}
return NULL;
}
条件(2)一般的二叉树 + 有指向父亲的指针
思路:规划为两个相交链表求交集。
代码:树使用兄弟孩子链表法存储。
struct CSNode
{
int m_nValue;
CSNode* m_pParent;
CSNode* m_pFirstChild;
CSNode* m_pNextSibling;
};
int NodeCount(CSNode* pNode)
{
assert(pNode);
int nLen = 0;
while(pNode)
{
nLen++;
pNode = pNode->m_pParent;
}
return nLen;
}
CSNode* LCA(CSNode*& pFNode,