PAT Advanced 1119 Pre- and Post-order Traversals (30 )
题目描述
Input Specification:
Output Specification:
Sample Input:
Sample Output:
解题思路
前序加上后序不能确定一颗二叉树的原因就是,如果一个结点只有一个孩子,那么这个孩子可以是左/右子树。本来想根据这个特点重建二叉树的,后来发现第3个N=30的测试点过不去。。后来参考了大佬的思路,对哦,不用重建二叉树就可以直接得到中序遍历。。
Code
- AC代码
#include<bits/stdc++.h>
using namespace std;
vector<int> pre, post, in;
int N;
bool check(int prel, int prer, int postl, int postr) {
if(prel > prer) return false;
else if(prel == prer) {
in.push_back(pre[prel]);
return true;
}
int i = postl;
for(; i<=postr; i++) {
if(pre[prel+1] == post[i]) break;
}
bool result = check(prel+1, prel+1+i-postl, postl, i);
in.push_back(pre[prel]);
result = check(prel+1+i-postl+1, prer, i+1, postr-1) && result;
return result;
}
int main() {
//freopen("in.txt", "r", stdin);
cin >> N;
pre.resize(N);
post.resize(N);
for(int i = 0; i<N; i++) {
cin >> pre[i];
}
for(int i = 0; i<N; i++) {
cin >> post[i];
}
check(0, N-1, 0, N-1) ? cout << "Yes\n" : cout << "No\n";
for(int i = 0; i<N; i++) {
cout << in[i];
i != N-1 ? cout << ' ' : cout << '\n';
}
return 0;
}