L2-011. 玩转二叉树
和之前的题一样,只需要改动一点。
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <vector> #include <queue> using namespace std; const int maxn = 1e3+5; int a[maxn]; int b[maxn]; int floor1[maxn]; int tr[maxn<<2]; int retr[maxn<<2]; int n; void build(int x,int al,int ar,int bl,int br) { if(ar<al||br<bl) return; if(al == ar) { tr[x] = a[al]; return; } for(int i = 1; i<=n; i++) { if(a[i]==b[bl]) { tr[x] = a[i]; build(2*x,i+1,ar,bl+i-al+1,br); //只需要将之前的代码上下两句调换即可。 build(2*x+1,al,i-1,bl+1,bl+i-al); break; } } } void bfs(int x) //按层序遍历 { queue<int> q; q.push(x); int ans = 1; while(!q.empty()) { int y = q.front(); q.pop(); if(tr[y]==0) continue; floor1[ans++] = tr[y]; q.push(2*y); q.push(2*y+1); } } int main() { memset(tr,0,sizeof(tr)); scanf("%d",&n); for(int i = 1; i<=n; i++) { scanf("%d",&a[i]); } for(int i = 1; i<=n; i++) { scanf("%d",&b[i]); } build(1,1,n,1,n); retr[1] = tr[1]; bfs(1); for(int i = 1; i<n; i++) printf("%d ",floor1[i]); printf("%d\n",floor1[n]); return 0; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步