迭代版的前序遍历,每输出一个元素,就要push一次;迭代版的中序遍历,每输出一个元素,就要pop一次。得到前序遍历和中序遍历的序列后,构造树,然后对树进行后序遍历。
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <cstdlib>
#include <stack>
#include <cstring>
using namespace std;
struct node {
int index;
node *left, *right;
};
node *insert(int index);
void postorder(node *root);
void deletetree(node *root);
node *rebuild(int *pre, int *in, int len);
int main(void) {
int n, i, index, pre[100], in[100], preindex = 0, inindex = 0;
char command[10];
node *root = nullptr;
bool flag = false;
stack<int> s;
scanf("%d", &n);
for (i = 0; i < n * 2; i++) {
scanf("%s", command);
if (!strcmp(command, "Push")) {
scanf("%d", &index);
s.push(index);
pre[preindex++] = index;
}
else if (!strcmp(command, "Pop")) {
in[inindex++] = s.top();
s.pop();
}
}
root = rebuild(pre, in, inindex);
postorder(root->left);
postorder(root->right);
printf("%d\n", root->index);
deletetree(root);
return 0;
}
void postorder(node *root) {
if (root) {
postorder(root->left);
postorder(root->right);
printf("%d ", root->index);
}
return;
}
void deletetree(node *root) {
if (root) {
deletetree(root->left);
deletetree(root->right);
delete root;
}
return;
}
node *rebuild(int *pre, int *in, int len) {
node *tmp;
int mid1, mid2, i;
if (len == 0) {
return nullptr;
}
else if (len == 1) {
tmp = new node;
tmp->index = pre[0];
tmp->left = tmp->right = nullptr;
return tmp;
}
tmp = new node;
tmp->index = pre[0];
for (mid2 = 0; mid2 < len; mid2++) {
if (in[mid2] == pre[0]) {
break;
}
}
tmp->left = rebuild(pre + 1, in, mid2);
tmp->right = rebuild(pre + mid2 + 1, in + mid2 + 1, len - mid2 - 1);
return tmp;
}