重构二叉树,已知前序和中序,输出后序。
#include <iostream>
#include <cstring>
using namespace std;
struct treeNode
{
treeNode();
char letter;
treeNode* left;
treeNode* right;
};
treeNode::treeNode()
{
left=NULL;
right=NULL;
}
void AddNode(treeNode* node,bool left,bool right,char ch)
{
treeNode* tmpNode=new treeNode;
tmpNode->letter=ch;
if(true==left)
{
node->left=tmpNode;
}
else
{
node->right=tmpNode;
}
}
int findSameLetter(char letter,char str[],int startPoint)
{
int len=0;
for(int i=startPoint;str[i]!='/0';i++)
{
if(str[i]==letter)
{
break;
}
len++;
}
return len;
}
void BuildTree(treeNode* cNode,char preStr[],char inStr[], int preStart,int inStart,int preEnd,int inEnd)
{
//把preStr[preStart]建立新的节点
cNode->letter=preStr[preStart];
//调用findSameStr[]找到左子树的共同字符串长度
int len;
len=findSameLetter(cNode->letter,inStr,inStart);
if(len>0)//对左子树调用BuildTree
{
cNode->left=new treeNode;
BuildTree(cNode->left,preStr,inStr,preStart+1,inStart,preStart+len,inStart+len-1);
}
//对右子树调用BuildTree
if(preStart+len+1<=preEnd)
{
cNode->right=new treeNode;
BuildTree(cNode->right,preStr,inStr,preStart+len+1,inStart+len+1,preEnd,inEnd);
}
}
void PostTravel(treeNode* node)
{
if(NULL!=node)
{
PostTravel(node->left);
PostTravel(node->right);
cout<<node->letter;
}
return;
}
int main()
{
char preStr[27];
char inStr[27];
int len;
treeNode* rootNode=NULL;
while(cin>>preStr>>inStr)
{
len=strlen(preStr)-1;
rootNode=new treeNode;
BuildTree(rootNode,preStr,inStr,0,0,len,len);
PostTravel(rootNode);
cout<<endl;
}
return 0;
}