原题链接:A1086 Tree Traversals Again
#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef struct BiTNode
{
int data;
struct BiTNode *lChild, *rChild;
}BiTNode, *BiTree;
BiTree ROOT = NULL;//根节点
int N, S[50], top = 0, Pre[50], In[50], flag = 0;//S是栈
char str[10];
BiTree creatTree(int preL, int preR, int inL, int inR)//根据先序和中序建树
{
if(preL < preR && inL < inR)
{
BiTree q = new BiTNode;
q->data = Pre[preL];
if(ROOT == NULL) ROOT = q;//保存根节点
int k = inL;
while(k < inR && In[k] != Pre[preL]) k++;
q->lChild = creatTree(preL+1, preL+k-inL+1, inL, k);
q->rChild = creatTree(preL+k-inL+1, preR, k+1, inR);
return q;
}
return NULL;
}
void postOrder(BiTree T)//后序遍历,用flag控制输出格式
{
if(T == NULL) return ;
postOrder(T->lChild);
postOrder(T->rChild);
if(flag) printf(" ");
printf("%d", T->data);
flag = 1;
}
int main()
{
scanf("%d", &N);
for(int i=0, j=0, k=0; i<2*N; i++)
{
scanf("%s", str);
if(strcmp(str, "Pop"))//若输入不是pop则入栈、先序
{
scanf("%d", &S[top]);
Pre[j++] = S[top++];
}
else In[k++] = S[--top];//否则出桟、中序
}
creatTree(0, N, 0, N);//建树、后序遍历输出
postOrder(ROOT);
return 0;
}