1086 Tree Traversals Again

#include<bits/stdc++.h>
using namespace std;
struct Node{
	int value;
	Node* left;
	Node* right;
};
vector<int> pre,in,pos,qu;
Node* build(int prel,int prer,int inl,int inr){
	if(prel>prer) return 0;
	Node* root=new Node;
	root->value=pre[prel];
	root->left=NULL;
	root->right=NULL;
	int k;
	for(k=inl;k<=inr;k++){
		if(pre[prel]==in[k]){
			break;
		}
	}
	int numleft=k-inl;
	root->left=build(prel+1,prel+numleft,inl,k-1);
	root->right=build(prel+numleft+1,prer,k+1,inr);
	return root;
}
void postra(Node* root){
	if(root==NULL) return;
	postra(root->left);
	postra(root->right);
	pos.push_back(root->value);
}
int main(){
	#ifndef ONLINE_JUDGE
	freopen("in.txt","r",stdin);
	#endif
	int n;
	cin>>n;
	for(int i=0;i<n*2;i++){
		string temp;
		int t;
		cin>>temp;
		if(temp=="Push"){
			cin>>t;
			pre.push_back(t);
			qu.push_back(t);
		}else if(temp=="Pop"){
			in.push_back(qu[qu.size()-1]);
			qu.erase(qu.begin()+qu.size()-1);
		}
	}
	Node* root=build(0,n-1,0,n-1);
	postra(root);
	for(int i=0;i<n;i++){
		if(i==0) cout<<pos[i];
		else cout<<' '<<pos[i];
	}
	cout<<endl;
	return 0;
}

玄学垃圾!

猜你喜欢

转载自blog.csdn.net/csg3140100993/article/details/81741757