知识点:二叉树
属于是PAT上面不错的题,考察对二叉树遍历的理解,这道题只要想清楚什么情况出现了二叉树就不唯一了就可以做出来了。
然后就是PAT的坑,格式错误,最后要输出换行,因为知道PAT要求严格,所以最后一行最后一个数据后面什么都不敢输出的,然后因为没有输出换行错了。
#include <bits/stdc++.h>
using namespace std;
struct node {
int val;
int lchild, rchild;
} tree[35];
int tot, pre[35], post[35], cnt;
bool flag = true;
int create(int prel, int prer, int postl, int postr) {
if (prel > prer) return -1;
int root = ++tot;
tree[root].val = pre[prel];
int k = postl - 1;
for (int i = postl; i <= postr - 1; i++) {
if (pre[prel + 1] == post[i]) { k = i; break; }
}
if (k == postr - 1 && postr != postl) flag = false;
int numleft = k - postl + 1;
tree[root].lchild = create(prel + 1, prel + numleft, postl, postl + numleft - 1);
tree[root].rchild = create(prel + numleft + 1, prer, postl + numleft, postr - 1);
return root;
}
void inorder(int root) {
if (root == -1) return;
inorder(tree[root].lchild);
if (cnt++) cout << " ";
cout << tree[root].val;
inorder(tree[root].rchild);
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) cin >> pre[i];
for (int i = 0; i < n; i++) cin >> post[i];
int root = create(0, n - 1, 0, n - 1);
cout << (flag ? "Yes" : "No") << endl;
inorder(root);
cout << endl;
return 0;
}