给后序输出前序:
#include <bits/stdc++.h>
using namespace std;
#define ENDL '\n'
const int maxn = 1e6 + 10;
int n, cur;
int a[maxn], ans[maxn];
void dfs(int i) {
if (i > n) return;
dfs(i * 2); //先填左子树
dfs(i * 2 + 1);
ans[i] = a[cur++];
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
cur = 1;
dfs(1);
cout << ans[1];
for (int i = 2; i <= n; i++) cout << " " << ans[i];
cout << ENDL;
return 0;
}
镜像树+前序找后序:
L2-004 这是二叉搜索树吗? - 团体程序设计天梯赛-练习集 (pintia.cn)
#include<bits/stdc++.h>
using namespace std;
const int N = 1e3+10;
int a[N],n;
vector<int> ans;
void dfs1(int root,int tail){
if(root > tail) return;
int l = root + 1,r = tail;
while(a[l] < a[root] && l <= tail) l++;
while(a[r] >= a[root] && r > root) r--;
if(l - r != 1) return;//因为要刚好越过分界线
dfs1(root+1,r);//向左子树递归
dfs1(l,tail);//向右子树递归
ans.push_back(a[root]);//将当前的父节点放入答案
//如果我们发现是一个二叉搜索树那么ans存的就是后根遍历的结果,
//因为是递归左右子树后才放入ans中的,下面同理
}
void dfs2(int root,int tail){
if(root > tail) return;
int l = root + 1,r = tail;
while(a[l] >= a[root] && l <= tail) l++;
while(a[r] < a[root] && r > root) r--;
if(l - r != 1) return;
dfs2(root+1,r);
dfs2(l,tail);
ans.push_back(a[root]);
}
int main()
{
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
cin>>n;
for(int i = 0;i < n; ++i) cin>>a[i];
dfs1(0,n-1);
if(ans.size() != n){
ans.clear();
dfs2(0,n-1);
}
if(ans.size() == n) {
printf("YES\n%d",ans[0]);
for(int i = 1;i < n;i++) printf(" %d",ans[i]);
} else {
cout<<"NO"<<endl;
}
return 0;
}