L2-006. 樹的遍曆(利用後序中序還原二叉樹)

來源:互聯網
上載者:User

題目連結:https://www.patest.cn/contests/gplt/L2-006

思路分析:後序可以知道樹根,然後在中序中找出樹根,又可以確定左右子樹,然後遞迴地對左右子樹進行分解,即可還原出二叉樹。最後把建好的樹BFS一遍就可以寫出層次遍曆了。

AC代碼如下:

#include<iostream>#include<vector>#include<queue>#include<cstring>#include<cstdio>using namespace std;const int maxn=3005;int tree[maxn];void build(int rt,vector<int>a,vector<int>b)//遞迴建樹{    if(a.size()==0) return ;//遞迴出口    int p=0;    for(int i=0;i<b.size();i++)//找出根        if(b[i]==a[a.size()-1]) p=i;    vector<int>al,ar,bl,br;    for(int i=0;i<p;i++) al.push_back(a[i]);//左子樹的後序遍曆序列    for(int i=p;i<a.size()-1;i++) ar.push_back(a[i]);//右子樹的後序遍曆序列    for(int i=0;i<p;i++) bl.push_back(b[i]);//左子樹的中序遍曆序列    for(int i=p+1;i<b.size();i++) br.push_back(b[i]);//右子樹的中序遍曆序列    tree[rt]=b[p];//建根    build(rt<<1,al,bl);//遞迴建左子樹    build(rt<<1|1,ar,br);//遞迴建右子樹}void bfs()//用bfs層次遍曆{    queue<int>q;    int root=1;    q.push(root);    int f=0;    while(q.size())    {        if(f++) cout<<" ";        root=q.front();        cout<<tree[root];        q.pop();        if(tree[root<<1]!=-1) q.push(root<<1);        if(tree[root<<1|1]!=-1) q.push(root<<1|1);    }    cout<<endl;}int main(){    //freopen("in.txt","r",stdin);    int n,x;    while(cin>>n)    {        memset(tree,-1,sizeof(tree));        vector<int>a,b;        for(int i=0;i<n;i++) cin>>x,a.push_back(x);        for(int i=0;i<n;i++) cin>>x,b.push_back(x);        build(1,a,b);        bfs();    }    return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.