输入前序遍历序列和中序遍历序列,输出后序遍历序列
#include <iostream>
#include <cstring>
using namespace std;
struct TreeNode
{
char ch;
TreeNode *lchild;
TreeNode *rchild;
};
void PostTree(char *preStr,char *inStr,int length)
{
int rootidx = 0;
TreeNode *root = new TreeNode;
if(length == 0)
{
return;
}
root->ch = *preStr;
for(rootidx = 0; rootidx <length;rootidx++)
{
if(*preStr == inStr[rootidx]) //寻找中序遍历序列中根节点的索引
{
break;
}
}
PostTree(preStr + 1,inStr,rootidx); //左子树递归
PostTree(preStr+rootidx+1,inStr+rootidx+1,length-rootidx-1); //右子树递归
cout<<root->ch;
return;
}
int main()
{
char pretree[26] = {'\0'}; //存储先序遍历结果
char intree[26] = {'\0'}; //存储中序遍历结果
char temp[26] = {0};
while(cin.getline(temp,26))
{
strncpy(pretree,temp,26);
cin.getline(temp,26);
strncpy(intree,temp,26);
PostTree(pretree,intree,strlen(pretree));
cout<<endl;
}
return 0;
}