重点在于,结合栈来看,实现的是中序遍历,抛开栈,单看这些数字的顺序,则是前序遍历的结果,因此可以直接用前序中序转后序算法。
#include<cstdio>
#include<iostream>
#include<vector>
#include<string>
#include<cmath>
#include<stack>
#define maxn 30
using namespace std;
struct node {
int data;
node *left, *right;
};
vector<int> preo, ino, posto; // pre-order, in-order
node* buildtree(int prel, int prer, int inl, int inr) {
if (prel >= prer) return NULL;
int temp = preo[prel];
node* root = new node;
root->data = temp;
int i;
for (i = inl; i < inr; i++) {
if (ino[i] == temp) break;
}
int len = i - inl;
root->left = buildtree(prel + 1, prel + 1 + len, inl, i);
root->right = buildtree(prel + 1 + len, prer, i + 1, inr);
return root;
}
void postorder(node *root) {
if (root == NULL) return;
postorder(root->left);
postorder(root->right);
posto.push_back(root->data);
return;
}
int main() {
int N, lines, a;
string str;
stack<int> sta;
cin >> N;
lines = 2 * N;
node *root;
while (lines--) {
cin >> str;
if (str == "Push") {
cin >> a;
preo.push_back(a);
sta.push(a);
}
else {
int t = sta.top();
ino.push_back(t);
sta.pop();
}
}
root = buildtree(0, N, 0, N);
postorder(root);
for (int i = 0; i < posto.size(); i++) {
printf("%d", posto[i]);
if (i != posto.size() - 1) printf(" ");
else printf("\n");
}
return 0;
}