题干:1138 Postorder Traversal (25 分)
- 题解:做了35分钟,得了20分,我其他篇博客有很多做题时候的心路历程和经验。。。。都是非常真实的感受,但是感觉没必要每篇都重复写,感兴趣的话到专栏看就好了,我把链接放在下面,做一个佛系的考生和博主。。。(知道自己到底想要什么,往往比达成一个所谓的“目标”更有幸福感)
- PAT冲刺备考
// A1138.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <bits/stdc++.h>
using namespace std;
vector<int> pre;
vector<int> in;
struct node {
int val;
node* lc;
node* rc;
node() {
val = -1;
lc = rc = NULL;
}
};
//vector<int> post;
node* build(int root, int start, int end) {
if (start > end) {
return NULL;
}
int i;
for (i = 0; i < in.size(); i++) {
if (in[i] == pre[root]) {
break;
}
}
node* t = new node();
t->val = pre[root];
t->lc = build(root + 1, start, i - 1);
t->rc = build(root + 1+i-start, i + 1, end);
return t;
}
bool flag = false;
void post_order(node* root) {
if (flag == true) {
return;
}
if (root->lc != NULL)post_order(root->lc);
if(root->rc != NULL)post_order(root->rc);
if (flag == false) {
cout << root->val;
//post.push_back(root->val);
flag = true;
}
}
int main()
{
#ifndef ONLINE_JUDGE
FILE* s;
freopen_s(&s, "in.txt", "r", stdin);
#endif // !ONLINE_JUDGE
int n;
cin >> n;
pre.resize(n); in.resize(n);
for (int i = 0; i < n; i++) {
cin >> pre[i];
}
for (int i = 0; i < n; i++) {
cin >> in[i];
}
node* root;
root = build(0, 0, n - 1);
post_order(root);
return 0;
}