L2-006 树的遍历
生活随笔
收集整理的這篇文章主要介紹了
L2-006 树的遍历
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一棵二叉樹的后序遍歷和中序遍歷,請你輸出其層序遍歷的序列。這里假設鍵值都是互不相等的正整數。
輸入格式:
輸入第一行給出一個正整數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題解:
我發現pta就喜歡考前序后序這種題。。。
給出后序+中序,求層次遍歷
先序,后序遍歷可以確定根節點。
中序遍歷可以確定左子樹和右子樹。
不斷遞歸就查找就可以
代碼:
#include<bits/stdc++.h> using namespace std; const int maxn=40; int mid[maxn]; int post[maxn]; struct node{int lson,rson; }f[maxn]; int build(int lmid,int rmid,int lpost,int rpost){ //中序遍歷 后序遍歷 //后序遍歷確定根 //先序,后序遍歷可以確定根節點。 //中序遍歷可以確定左子樹和右子樹。if(lmid>rmid)return 0;int root=post[rpost];int fa=lmid; while(mid[fa]!=root)fa++;//確定根 int len=fa-lmid;//確定左子樹長度f[root].lson=build(lmid,fa-1,lpost,lpost+len-1);//左子樹 f[root].rson=build(fa+1,rmid,lpost+len,rpost-1);//右子樹 return root; } void bfs(int x) {queue<int>q;vector<int>v;q.push(x);while(!q.empty()){int w=q.front();q.pop();if(!w)break;v.push_back(w);if(f[w].lson)q.push(f[w].lson);if(f[w].rson)q.push(f[w].rson);}int len=v.size();for(int i=0;i<len;i++){if(i!=len-1)printf("%d ",v[i]);else cout<<v[i];}return ; } int main() {int n;cin>>n;for(int i=0;i<n;i++)cin>>post[i];//后序 for(int i=0;i<n;i++)cin>>mid[i];//中序int root=post[n-1];build(0,n-1,0,n-1);bfs(root);return 0; }總結
以上是生活随笔為你收集整理的L2-006 树的遍历的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 头条文章新手经常遇到的问题头条文章新手经
- 下一篇: 点分治(树分治)