題目鏈接:https://pintia.cn/problem-sets/994805046380707840/problems/994805069361299456
題意:給出一個二叉樹的結點數目n,后序遍歷序列post,中序遍歷序列in,求其層序遍歷序列。
思路:首先給二叉樹每個結點一個編號,按照層序遍歷的順序一次編號,即一個編號為i的結點其左子樹根節點編號為2*i+1,其右子樹根節點的編號為2*i+2(二叉樹的根節點為0),因為30層的二叉樹編號達到了2*30-1,不能直接用數組存,會爆空間。我們可以用優先隊列和二元組pair來存,pair的first存結點編號,second存該結點的值。之后就暴力遞歸了,每次將根節點入隊,然后依次對其左子樹、右子樹遞歸調用。
AC代碼:
#include<bits/stdc++.h> using namespace std;int post[35],in[35]; int n; typedef pair<int,int> PII; priority_queue<PII,vector<PII>,greater<PII> > pq;void getc(int l,int r,int root,int index){if(l>r) return;int i=l;while(in[i]!=post[root]) ++i;pq.push(make_pair(index,post[root]));getc(l,i-1,root-1-r+i,2*index+1);getc(i+1,r,root-1,2*index+2); }int main(){scanf("%d",&n);for(int i=0;i<n;++i)scanf("%d",&post[i]);for(int i=0;i<n;++i)scanf("%d",&in[i]);getc(0,n-1,n-1,0);PII p=pq.top();pq.pop();printf("%d",p.second);while(!pq.empty()){p=pq.top();pq.pop();printf(" %d",p.second);}printf("\n");return 0; }
?