题目:在二叉树中给出两个已知结点,求这两个结点的最低公共祖先
解析:具体实现过程请参考以下代码
完整代码及其测试:
#include<iostream>
#include<list>
using namespace std;
//定义二叉树的节点
struct BinaryTreeNode
{
char m_nvalue;
BinaryTreeNode* m_pleft;
BinaryTreeNode* m_pright;
};
//创建值为value的节点
BinaryTreeNode* CreateBinaryTreeNode(char value)
{
BinaryTreeNode* p = new BinaryTreeNode();
p->m_nvalue = value;
p->m_pleft = NULL;
p->m_pright = NULL;
return p;
}
//设置左孩子
void SetLeftchild(BinaryTreeNode* pRoot, BinaryTreeNode* lchild)
{
if (pRoot == NULL)
{
return;
}
pRoot->m_pleft = lchild;
}
//设置右孩子
void SetRightchild(BinaryTreeNode* pRoot, BinaryTreeNode* rchild)
{
if (pRoot == NULL)
{
return;
}
pRoot->m_pright= rchild;
}
//保存从根节点到某节点的路径(最重要函数)
bool getPath(BinaryTreeNode* pRoot, BinaryTreeNode* pNode, list<BinaryTreeNode*> &List)
{
if (pRoot == NULL || pNode == NULL)
{
return false;
}
if (pRoot == pNode)
{
List.push_back(pRoot);
return true;
}
List.push_back(pRoot);
bool result = getPath(pRoot->m_pleft, pNode, List);
if (!result)
{
result = getPath(pRoot->m_pright, pNode, List);
}
if (!result)
{
List.pop_back();
}
return result;
}
//求两个节点的最低公共祖先
BinaryTreeNode* getCommonParent(BinaryTreeNode* pRoot, BinaryTreeNode* pNode1, BinaryTreeNode* pNode2)
{
list<BinaryTreeNode*> List1;
list<BinaryTreeNode*> List2;
bool result1 = getPath(pRoot, pNode1, List1);
bool result2 = getPath(pRoot, pNode2, List2);
if (result1 == false || result2 == false)
{
return NULL;
}
BinaryTreeNode* commonParent = NULL;
list<BinaryTreeNode*>::iterator ite1 = List1.begin();
list<BinaryTreeNode*>::iterator ite2 = List2.begin();
for (; ite1 != List1.end() && ite2 != List2.end(); ite1++, ite2++)
{
if (*ite1 == *ite2)
{
commonParent = *ite1;
}
else
{
break;
}
}
return commonParent;
}
// ====================测试代码====================
void Test()
{
//创建一棵如下所示的二叉树
// A
// / \
// B C
// / \
// D E
// / \ / \
// F G H I
BinaryTreeNode* pA = CreateBinaryTreeNode('A');
BinaryTreeNode* pB = CreateBinaryTreeNode('B');
BinaryTreeNode* pC = CreateBinaryTreeNode('C');
BinaryTreeNode* pD = CreateBinaryTreeNode('D');
BinaryTreeNode* pE = CreateBinaryTreeNode('E');
BinaryTreeNode* pF = CreateBinaryTreeNode('F');
BinaryTreeNode* pG = CreateBinaryTreeNode('G');
BinaryTreeNode* pH = CreateBinaryTreeNode('H');
BinaryTreeNode* pI = CreateBinaryTreeNode('I');
SetLeftchild(pA, pB);
SetRightchild(pA, pC);
SetLeftchild(pB, pD);
SetRightchild(pB, pE);
SetLeftchild(pD, pF);
SetRightchild(pD, pG);
SetLeftchild(pE, pH);
SetRightchild(pE, pI);
BinaryTreeNode* p = getCommonParent(pA, pF, pH);
if (p != NULL)
{
cout << "Common Parent is " << p->m_nvalue << "!" << endl;
}
}
int main()
{
Test();
system("pause");
return 0;
}
运行结果:
Common Parent is B!
请按任意键继续. . .