#include<bits/stdc++.h>
using namespace std;
const int maxn = 50;
struct Node{
int data;
Node* lchild;
Node* rchild;
};
stack<int> s;
int in[maxn], pre[maxn];
int n, num = 0;
void PostOrder(Node* root){
if(root == NULL){
return;
}
PostOrder(root->lchild);
PostOrder(root->rchild);
printf("%d", root->data);
if(num < n-1){
printf(" ");
num++;
}
}
Node* create(int preL, int preR, int inL, int inR){
if(preL > preR){
return NULL;
}
Node* now = new Node;
now->data = pre[preL];
int k;
for(k = 0; k < preR; k++){
if(pre[preL] == in[k]){
break;
}
}
int numLeft = k - inL;
now->lchild = create(preL+1, preL+numLeft, inL, k-1);//这里只能够是k-1,不用加上inL
now->rchild = create(preL+numLeft+1, preR, k+1, inR);
return now;
}
int main(){
scanf("%d", &n);
int num1 = 0, num2 = 0;
//char str[5];
string str;
for(int i = 0; i < 2*n; i++){
cin >> str;
if(str.compare("Push") == 0){
int data1;
scanf("%d", &data1);
pre[num1++] = data1;
s.push(data1);
}else{
in[num2++] = s.top();
s.pop();
}
}
Node* root = create(0, n-1, 0, n-1);
PostOrder(root);
return 0;
}
A1086 Tree Traversals Again (25分)
原文:https://www.cnblogs.com/tsruixi/p/12313691.html