日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

PAT甲级1127 ZigZagging on a Tree (30分):[C++题解]之字形层次遍历树bfs实现一层一层读入

發布時間:2025/4/5 c/c++ 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 PAT甲级1127 ZigZagging on a Tree (30分):[C++题解]之字形层次遍历树bfs实现一层一层读入 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

    • 題目分析
    • 題目鏈接

題目分析

分析

給定中序遍歷和后序遍歷,先建樹; 后面就是寫一個bfs,層序遍歷稍微改改即可。

bfs要做的修改是如何一層一層的讀入。令根結點是第一層,本題的之字形遍歷就是奇數層需要反轉。

bfs如下
這里用的是數組模擬隊列q,hh表示隊頭,tt表示隊尾。

為了實現一層一層讀入, head表示這一層的頭結點下標,tail表示這一層尾結點的下標。while(hh <= tail)表示一直在讀入某一層。

void bfs(int root){int hh = 0 ,tt = 0;q[0] =root;int step = 0; //根結點是第1層while(hh<= tt){ //隊列不空int head =hh , tail = tt; //這一層的端點存下來//先存一層while( hh <= tail){//如果hh小于等于tail,就把下一層先存起來int t = q[hh++];if(l.count(t)) q[++tt] = l[t];if(r.count(t)) q[++tt] = r[t];}//奇數層就反轉if( ++ step &1) reverse(q+head,q+tail+1); }cout<<q[0];for(int i=1;i<n;i ++) cout<<" "<<q[i];}

ac代碼

#include<bits/stdc++.h> using namespace std;const int N = 40;unordered_map<int,int> l ,r ,pos; int n ,in[N], post[N]; int q[N];int dfs(int il ,int ir, int pl ,int pr){int root = post[pr];int k = pos[root];if(il< k) l[root] = dfs(il, k-1, pl, pl+k-1-il);if(k<ir) r[root] =dfs(k+1,ir, pl+k-il, pr-1);return root; }void bfs(int root){int hh = 0 ,tt = 0;q[0] =root;int step = 0; //根結點是第1層while(hh<= tt){ //隊列不空int head =hh , tail = tt; //這一層的端點存下來//先存一層while( hh <= tail){//如果hh小于等于tail,就把下一層先存起來int t = q[hh++];if(l.count(t)) q[++tt] = l[t];if(r.count(t)) q[++tt] = r[t];}//奇數層就反轉if( ++ step &1) reverse(q+head,q+tail+1); }cout<<q[0];for(int i=1;i<n;i ++) cout<<" "<<q[i];}int main(){cin>> n;for(int i = 0; i<n; i++){cin>>in[i];pos[in[i]] =i;}for(int i =0; i< n; i++) cin>> post[i];int root = dfs( 0, n-1, 0, n-1);bfs(root);}

題目鏈接

PAT甲級1127 ZigZagging on a Tree (30分)

總結

以上是生活随笔為你收集整理的PAT甲级1127 ZigZagging on a Tree (30分):[C++题解]之字形层次遍历树bfs实现一层一层读入的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。