Sample Input:
6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop
Sample Output:
3 4 2 6 5 1
//由前序和中序建树,后序遍历树
#include <iostream>
#include <string>
#include <stack>
#include <vector>
using namespace std;
typedef struct TreeNode *Tree;
int flag = 0;
vector<int> vecPre, vecIn;
struct TreeNode {
int Id;
Tree Left;
Tree Right;
};
void BuiltTree(int, int, int, int, Tree &);
void PostorderT(Tree);
int Find(vector<int> &, int);
int main() {
Tree R = NULL;
int n;
stack<int> st;
string s;
scanf("%d\n", &n);
if (n) {
for (int i = 0; i < 2 * n; i++) {
getline(cin, s);
if (s.size() > 3) {
vecPre.push_back(s[s.size() - 1] - '0');
st.push(s[s.size() - 1] - '0');
}
else {
vecIn.push_back((st.top()));
st.pop();
}
}
BuiltTree(0, n - 1, 0, n - 1, R);
PostorderT(R);
}
vecPre.clear();
vecIn.clear();
return 0;
}
void BuiltTree(int pbegin, int pend, int ibegin, int iend, Tree &r) {
if (ibegin <= iend && pbegin <= pend) {
if (!r) {
r = new TreeNode();
r->Id = vecPre[pbegin];
r->Left = NULL;
r->Right = NULL;
}
int pos = Find(vecIn, vecPre[pbegin]);
BuiltTree(pbegin + 1, pbegin + pos - ibegin, ibegin, pos - 1, r->Left);
BuiltTree(pend - iend + pos + 1, pend, pos + 1, iend, r->Right);
}
}
void PostorderT(Tree r) {
stack<Tree> s;
Tree cur = r, previsited = NULL;
while (cur != NULL || !s.empty()) {
while (cur != NULL) {
s.push(cur);
cur = cur->Left;
}
cur = s.top();
if (cur->Right == NULL || cur->Right == previsited) {
if (flag)
printf(" ");
else flag = 1;
printf("%d", cur->Id);
previsited = cur;
s.pop();
cur = NULL;
}
else cur = cur->Right;
}
}
int Find(vector<int> &v, int n) {
int i;
for (i = 0;i != v.size();i++) {
if (v[i] == n)
break;
}
return i;
}
//直接由前序序列和中序序列得到后序序列
#include <iostream>
#include <cstring>
#include <stack>
#include <vector>
using namespace std;
vector<int> vecPre, vecIn, vecPost;
void solve(int preS, int inS, int n);
int main() {
int n;
scanf("%d\n", &n);
char str[5];
stack<int> st;
if (n) {
for (int i = 0; i < 2 * n; i++) {
scanf("%s", str);
if (strlen(str) == 4) {
int num;
scanf("%d", &num);
vecPre.push_back(num);
st.push(num);
}
else {
vecIn.push_back((st.top()));
st.pop();
}
}
}
solve(0, 0, n);
printf("%d", vecPost[0]);
for (int i = 1; i < n; i++)
printf(" %d", vecPost[i]);
return 0;
}
void solve(int preS, int inS, int n) {
if (n == 0) return;
int i, R, L;
for (i = 0;i < n;i++) {
if (vecIn[inS + i] == vecPre[preS]) break;
}
L = i;
R = n - 1 - L;
solve(preS + 1, inS, L);
solve(preS + 1 + L, inS + 1 + L, R);
vecPost.push_back(vecPre[preS]);
}