本題的關鍵是對所給樣例的理解,看了算法筆記才明白,push的次序是先序遍歷順序,pop的次序是中序遍歷順序.其餘跟A1020一樣.
A1020通過後序、中序遍歷獲取二叉樹
A1086通過先序、中序遍歷獲取二叉樹
#include<cstdio>
#include<cstdlib>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<string>
#include<algorithm>
using namespace std;
const int maxn=35;
int flag,n,preorder[maxn],inorder[maxn],pre=1,in=1;
struct node{
int data;
node* lchild;
node* rchild;
};
node* binary(int preL,int preR,int inL,int inR){
if(preL>preR){
return NULL;
}
node* root=new node;
root->data=preorder[preL];
int k=inL;
while(inorder[k]!=preorder[preL]){
k++;
}
int left_len=k-inL;
int right_len=inR-k;
root->lchild=binary(preL+1,preL+left_len,inL,k-1);
root->rchild=binary(preR-right_len+1,preR,k+1,inR);
return root; //忘了將根結點返回出去
}
void dfs(node* root){
if(root==NULL){
return;
}
dfs(root->lchild);
dfs(root->rchild);
if(root->data==flag){
printf("%d",root->data);
}else{
printf("%d ",root->data);
}
}
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt","r",stdin);
#endif
char str[5];
stack<int> s;
scanf("%d",&n);
for(int i=0;i<n*2;i++){
scanf("%s",str);
if(strcmp(str,"Push")==0){
scanf("%d",&preorder[pre++]);
s.push(preorder[pre-1]);
}else{
inorder[in++]=s.top();
s.pop();
}
}
node* root=binary(1,pre-1,1,in-1);
flag=root->data;
dfs(root);
return 0;
}