写到意识模糊的中序后序求层次遍历,受不了了去找别人的代码学。。。
#include<bits/stdc++.h> #define pb push_back #define mp make_pair #define fi first #define se second #define ll long long #define For(i,a,b) for(int i=a;i<=b;i++) #define Forr(i,a,b) for(int i=a;i>=b;i--) #define Fr(i,a,b) for(int i=a;i<b;i++) #define Frr(i,a,b) for(int i=a;i>b;i--) using namespace std; const int maxn=1005; inline ll read() { ll x=0,f=1;char ch=getchar(); while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();} while(ch>=‘0‘&&ch<=‘9‘){x=x*10+ch-‘0‘;ch=getchar();} return x*f; } vector<int>::iterator it; int a[maxn],b[maxn],L[maxn],R[maxn]; vector<int>vec[maxn]; int n; int maxx=0; int build(int l,int r,int zl,int zr) { if(l>r)return 0; int rt=a[r]; int tmp=0; for(int i=zl;i<=zr;i++) { if(b[i]==rt){ tmp=i;break; } } if(tmp) { R[rt]=build(r-(zr-tmp),r-1,tmp+1,zr); L[rt]=build(l,r-(zr-tmp)-1,zl,tmp-1); } return rt; } void dfs1(int x,int depth) { vec[depth].pb(x); maxx=max(maxx,depth); if(L[x])dfs1(L[x],depth+1); if(R[x])dfs1(R[x],depth+1); } int main() { n=read(); For(i,1,n) { a[i]=read(); } For(i,1,n) b[i]=read(); build(1,n,1,n);//cout<<22<<endl; dfs1(a[n],0); //cout<<222<<endl; for(int i=0;i<=maxx;i++) { for(int j=0;j<vec[i].size();j++) { if(i==maxx&&j+1==vec[i].size()) { cout<<vec[i][j]; } else cout<<vec[i][j]<<" "; } } }
原文:https://www.cnblogs.com/intwentieth/p/10439588.html