二叉树 ,中序遍历序列EDCBAHFG ,后序遍历序列是DBCEFGHA,它的前序遍历的序列是?
代码实现
#include <stdio.h>
#include <iostream>
using namespace std;
class BinaryTreeNode;
typedef BinaryTreeNode* BinaryTreeNodePtr;
//template<typename T>
class BinaryTreeNode
{
public:
BinaryTreeNode(char cChar)
:m_cObject(cChar)
,m_pParent(NULL)
,m_pRight(NULL)
,m_pLeft(NULL)
{
}
char m_cObject;
BinaryTreeNodePtr m_pParent;
BinaryTreeNodePtr m_pLeft;
BinaryTreeNodePtr m_pRight;
protected:
private:
};
//Note:参考
//char g_caInorder[] = {"EDCBAHFG"};
//char g_caPostorder[] = {"DBCEFGHA"};
BinaryTreeNodePtr Rebuild(BinaryTreeNodePtr paInorder[]
,BinaryTreeNodePtr paPostorder[]
,int iLen)
{
if (iLen<1)
return NULL;
if(1==iLen ){
paPostorder[iLen-1]->m_pLeft = paPostorder[iLen-1]->m_pRight = NULL;
return paPostorder[iLen-1];
}
int iLeftLen =0;
BinaryTreeNodePtr t_pNode= paPostorder[iLen-1];
for (;paInorder[iLeftLen]!=t_pNode && iLeftLen<iLen;iLeftLen++);
t_pNode->m_pLeft = Rebuild(paInorder ,paPostorder , iLeftLen );
t_pNode->m_pRight =Rebuild(paInorder+1+iLeftLen ,paPostorder+iLeftLen ,iLen-iLeftLen-1 );
return t_pNode;
};
void PreorderTraverse(BinaryTreeNodePtr pNode)
{
if (!pNode)
return;
std::cout<<pNode->m_cObject<<" -> ";
PreorderTraverse(pNode->m_pLeft);
PreorderTraverse(pNode->m_pRight);
}
int main()
{
#define g_iLen 8
// 0 , 1 2 3 4 5 6 7
BinaryTreeNode g_oaNode [g_iLen] = {'A' , 'B','C' , 'D' ,'E','F','G' , 'H'};
BinaryTreeNodePtr g_paInorder[g_iLen];
int g_iaInorder[g_iLen] = {4 , 3 , 2 ,1 , 0 ,7 , 5 , 6 };
BinaryTreeNodePtr g_paPostorder [g_iLen];
int g_iaPostorder[g_iLen] = {3 ,1 , 2,4 ,5 , 6 , 7 ,0};
for (int i =0; i<g_iLen; i++)
{
g_paInorder[i] = &g_oaNode[ g_iaInorder[i]];
g_paPostorder[i] = &g_oaNode[ g_iaPostorder[i]];
}
BinaryTreeNodePtr g_pHead = Rebuild(g_paInorder ,g_paPostorder , g_iLen );
if (g_pHead)
{
PreorderTraverse(g_pHead);
}
return 1;
}