l2-006 树的遍历
生活随笔
收集整理的這篇文章主要介紹了
l2-006 树的遍历
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
L2-006. 樹的遍歷
時間限制 400 ms 內存限制 65536 kB 代碼長度限制 8000 B 判題程序 Standard 作者 陳越給定一棵二叉樹的后序遍歷和中序遍歷,請你輸出其層序遍歷的序列。這里假設鍵值都是互不相等的正整數。
輸入格式:
輸入第一行給出一個正整數N(<=30),是二叉樹中結點的個數。第二行給出其后序遍歷序列。第三行給出其中序遍歷序列。數字間以空格分隔。
輸出格式:
在一行中輸出該樹的層序遍歷的序列。數字間以1個空格分隔,行首尾不得有多余空格。
輸入樣例: 7 2 3 1 5 7 6 4 1 2 3 4 5 6 7 輸出樣例: 4 1 6 3 5 7 2分析:
?這道題和pat l2-004簡直就是同一道題目啊...
?只不過那題是給你中序和先序...一個意思嘛
在先序或后序中,只要我們知道了左子樹或者右子樹的范圍,我們就可以找到根節點的值,從而在中序中找到根節點的位置,然后遞歸去做同樣的步驟就好啦。層序遍歷其實就是bfs啦!用用隊列就好了...
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn=1e5; 4 int mid[32], bk[32], tree[maxn]; 5 struct node{ 6 int l, r; 7 }a[maxn]; 8 int build(int la, int lb, int ra, int rb){ 9 if(la>lb) return 0; 10 int root=bk[rb]; 11 int p1, p2; 12 p1=la; 13 while(root!=mid[p1]) p1++; 14 p2=p1-la; 15 a[root].l=build(la, p1-1, ra, ra+p2-1); 16 a[root].r=build(p1+1, lb, ra+p2, rb-1); 17 return root; 18 } 19 void bfs(int x){ 20 int cnt=0; 21 queue<int>q; 22 q.push(x); 23 while(q.size()){ 24 int m=q.front(); q.pop(); 25 ++cnt==1? cout<<m:cout<<" "<<m; 26 if(a[m].l!=0) 27 q.push(a[m].l); 28 if(a[m].r!=0) 29 q.push(a[m].r); 30 } 31 } 32 int main(){ 33 int n; 34 cin>>n; 35 for(int i=0; i<n; i++) 36 cin>>bk[i]; 37 for(int i=0; i<n; i++) 38 cin>>mid[i]; 39 int root=build(0, n-1, 0, n-1); 40 bfs(root); 41 42 return 0; 43 }?
轉載于:https://www.cnblogs.com/ledoc/p/6591900.html
總結
以上是生活随笔為你收集整理的l2-006 树的遍历的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android运行过程简书,androi
- 下一篇: 11.m进制转十进制