1086 Tree Traversals Again (25 分)
题目入口:https://pintia.cn/problem-sets/994805342720868352/problems/994805380754817024
解题思想
注意到push
的顺序即为先序遍历顺序
pop
的顺序即为中序遍历顺序
已知先序中序求后序
到这里讲解结束
AC代码
#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <stack>
using namespace std;
stack<int> s;
vector<int> pre, in, post;
void postorder(int root, int start, int end){
if (start > end) return;
int i = start;
while (i < end && in[i] != pre[root]) i++;
postorder(root+1, start, i-1);
postorder(root+i-start+1, i+1, end);
post.push_back(pre[root]);
}
int main(){
int n, num, cnt = 0;
scanf("%d", &n);
char str[5];
while (~scanf("%s", str)){
if (strlen(str) == 4){
scanf("%d", &num);
pre.push_back(num);
s.push(num);
}
else {
in.push_back(s.top());
s.pop();
cnt++;
}
if (cnt == n) break;
}
postorder(0, 0, n-1);
printf("%d", post[0]);
for (int i = 1; i < n; i++)
printf(" %d", post[i]);
return 0;
}