#include <iostream>
#include <stack>
#include <string.h>
#define MAXN 30
using namespace std;
struct node
{
int data;
node* lchild;
node* rchild;
};
int in[MAXN],pre[MAXN];
int in_index=0,pre_index=0;
node* CreateT(int preL,int preR,int inL,int inR){
if(preL>preR) return NULL;
int tmp=pre[preL];
node* root=new node;
root->data=tmp;
int j;
for(j=inL;j<=inR;j++){
if(in[j]==tmp) break;
}
root->lchild=CreateT(preL+1,preL+j-inL,inL,j-1);
root->rchild=CreateT(preL+j-inL+1,preR,j+1,inR);
return root;
}
int p=0;
void postOrder(node* root){
if(!root) return;
postOrder(root->lchild);
postOrder(root->rchild);
if(p)printf(" %d",root->data);
else {
printf("%d",root->data);
p=1;
}
}
//二叉树的非递归遍历
int main(){
int N;
scanf("%d\n",&N);
string str;int op;
stack<int> s;
for(int i=0;i<2*N;i++){
cin>>str;
if(str=="Push"){
//只有push才需要二次读取数字,不能指定str[位数],可能是两位数以上,二次读取最易
cin>>op;
s.push(op);
//push()时输出是先序
pre[in_index++]=op;
}else{
op=s.top();
s.pop();
//pop()时输出时中序
in[pre_index++]=op;
}
}
node* root=CreateT(0,N-1,0,N-1);
postOrder(root);
return 0;
}
09-07
189
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交