重建二叉树
题目:
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建出二叉树并输入头结点。
二叉树定义如下:
struct BinaryNode
{
int m_nValue;
BinaryNode * m_pLeft;
BinaryNode * m_pRight;
};
本题考查中序遍历和前序遍历之间的联系,并且考察面试者的编程水准。
#include<iostream>
using namespace std;
struct BinaryNode
{
int m_nValue;
BinaryNode *m_pLeft;
BinaryNode *m_pRight;
};
BinaryNode * ConCore(int *beginPreOrder,int *endPreOrder,int *beginInOrder,int *endInOrder)
{
BinaryNode *pRoot=NULL;
int rootValue = beginPreOrder[0];
pRoot = new BinaryNode();
pRoot->m_nValue = rootValue;
pRoot->m_pLeft = pRoot->m_pRight = NULL;
if (beginPreOrder == endPreOrder)
{
if (beginInOrder == endInOrder && *beginPreOrder == *beginInOrder)
{
return pRoot;
}
else
throw exception("Invalid input");
}
int *InOrderPos = beginInOrder;
while (InOrderPos<=endInOrder && *InOrderPos!=rootValue)
{
++InOrderPos;
}
if (InOrderPos > endInOrder)
throw exception("Invalid input");
int LeftLegth = InOrderPos - beginInOrder;
if (LeftLegth > 0)
pRoot->m_pLeft = ConCore(beginPreOrder + 1, beginPreOrder + LeftLegth,beginInOrder,InOrderPos-1);
if (LeftLegth < endInOrder - beginInOrder)
pRoot->m_pRight = ConCore(beginPreOrder+LeftLegth+1,endPreOrder,InOrderPos+1,endInOrder);
return pRoot;
}
BinaryNode * Con(int *preOrder,int *InOrder,int length)
{
if (NULL == preOrder || NULL == InOrder || length <= 0)
return NULL;
return ConCore(preOrder,preOrder+length-1,InOrder,InOrder+length-1);
}
void PostOrder(BinaryNode *head)
{
if (head == NULL)
return;
PostOrder(head->m_pLeft);
PostOrder(head->m_pRight);
cout << head->m_nValue << " ";
}
int main()
{
int p1[] = {1,2,4,7,3,5,6,8};
int p2[] = {4,7,2,1,5,3,8,6};
BinaryNode *head = Con(p1,p2,8);
PostOrder(head);
return 0;
}