做这题时要先练过二叉树的非递归遍历,才会明白Push的序列是先序遍历序列,Pop的序列是中序遍历序列。
#include <stdio.h>
#include <stdlib.h>
typedef int Tree;
struct TNode{
int Data;
Tree Left;
Tree Right;
}T[30];
int *PreorderQ,P=-1;
int *InorderQ,I=-1;
int N,check=0;
void GetPreQandInQ()
{
scanf("%d",&N);
PreorderQ=(int*)malloc(sizeof(int)*N);
InorderQ=(int*)malloc(sizeof(int)*N);
char Operation[5],cData;
int Stack[N],Top=-1;
for(int i=0;i<2*N;i++)
{
scanf("%s",Operation);//两个连着的scanf,即使中间还有其他语句,也可以连着一起输入
if(Operation[1]=='u'){
scanf("%d",&PreorderQ[++P]);//空格虽然能结束字符串、整型的输入,但后面可以一直输入不会存储的符号
Stack[++Top]=PreorderQ[P];
}
else InorderQ[++I]=Stack[Top--];
}
}
void Postorder(int N,int *PreorderQ,int *InorderQ)//递归我还是用得不熟练
{
if(N==0) return;
int root=PreorderQ[0],i;
for(i=0;i<N;i++)
if(InorderQ[i]==root)
break;
Postorder(i,PreorderQ+1,InorderQ) ;
Postorder(N-i-1,PreorderQ+i+1,InorderQ+i+1);
if(check==0){
printf("%d",root);
check=1;
}
else printf(" %d",root);
}
int main()
{
GetPreQandInQ();
Postorder(N,PreorderQ,InorderQ);
return 0;
}