返回目录
题意
用栈模拟一颗二叉树的先序序列和中序序列,求该二叉树的后序遍历序列。
样例(可复制)
6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop
//output
3 4 2 6 5 1
注意点
- 本题模拟出的先序序列为:1 2 3 4 5 6
- 本题模拟出的先序序列为:3 2 4 1 6 5
- 本题与上题类似,增加了一个模拟过程,其中push进的数字序列是先序序列,pop出的数字序列是中序序列
- 建议读者模拟一遍create函数
- 输出先、中、后续遍历的方式采用递归较方便,其格式也很固定,可以记下来
#include<bits/stdc++.h>
using namespace std;
const int maxn=30;
int pre[maxn],in[maxn],post[maxn],n,num=0;
struct node{
int data;
node* lc;
node* rc;
};
node* create(int prel,int prer,int inl,int inr){
if(prel>prer)return NULL;
node* root=new node;
root->data=pre[prel];
int k;
for(k=inl;k<inr;k++){
if(in[k]==pre[prel])break;
}
int numleft=k-inl;
root->lc=create(prel+1,prel+numleft,inl,k-1);
root->rc=create(prel+numleft+1,prer,k+1,inr);
return root;
}
void postorder(node* root){
if(root==NULL)return;
postorder(root->lc);
postorder(root->rc);
printf("%d",root->data);
num++;
if(num<n)printf(" ");
}
int main(){
int tmp,preindex=0,inindex=0;
char a[5];
stack<int> st;
cin>>n;
for(int i=0;i<2*n;i++){
scanf("%s",a);
if(strcmp(a,"Push")==0){
scanf("%d",&tmp);
pre[preindex++]=tmp;
st.push(tmp);
}else{
in[inindex++]=st.top();
st.pop();
}
}
node* root=create(0,n-1,0,n-1);
postorder(root);
return 0;
}