L2-006 树的遍历 - 团体程序设计天梯赛-练习集
#include <bits/stdc++.h>
#define int long long
#define x first
#define y second
using namespace std;
const int N=35;
pair<int,int> tree[N];
int post[N],in[N];
int n;
int build(int la,int lb,int ra,int rb)
{if(la>lb||ra>rb)return 0;int root=post[rb];int p=la;while(in[p]!=root)p++;int cnt=p-la;tree[root].x=build(la,p-1,ra,ra+cnt-1);tree[root].y=build(p+1,lb,ra+cnt,rb-1);return root;
}
void dfs(int root)
{queue<int>q;vector<int>ans;q.push(root);while(q.size()){int t=q.front();q.pop();ans.push_back(t);if(tree[t].x) q.push(tree[t].x);if(tree[t].y) q.push(tree[t].y);}for(int i=0;i<ans.size();i++){if(!i) cout<<ans[i];elsecout<<' '<<ans[i];}
}
signed main()
{ios::sync_with_stdio(0);cin.tie(0),cout.tie(0);cin>>n;for(int i=1;i<=n;i++)cin>>post[i];for(int i=1;i<=n;i++)cin>>in[i];int root=build(1,n,1,n);dfs(root);
return 0;
}
L2-004 这是二叉搜索树吗? - 团体程序设计天梯赛-练习集
#include "bits/stdc++.h"
#define int long long
using namespace std;
vector<int>ans;
int n;
int a[1000000];
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+1) r--;if(l-r!=1) return;dfs1(root+1,r);dfs1(l,tail);ans.push_back(a[root]);
}
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]);
}
signed main()
{ios::sync_with_stdio(0);cin.tie(0),cout.tie(0);cin>>n;for(int i=0;i<n;i++)cin>>a[i];if(a[0]>a[1])dfs1(0,n-1);elsedfs2(0,n-1);if(ans.size()==n){cout<<"YES"<<'\n';for(int i=0;i<n;i++)if(i==n-1)cout<<ans[i];elsecout<<ans[i]<<' ';cout<<'\n';}elsecout<<"NO"<<'\n';
}