题目大意:给出一颗二叉树的中序和后序,打印出层序遍历结果。
解题思路:已知二叉树后序和中序遍历结果,可得二叉树唯一。故本题的思路就是利用中序和后续来构建二叉树,利用BFS遍历二叉树即可获得层序遍历结果。其中比较关键的一步是利用中序和后续来建立二叉树。为了较好地阐述代码,下图解释了代码注释中的 区间计算 的参数由来。
题目链接:https://www.patest.cn/contests/pat-a-practise/1020
#include <iostream>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
#include <stack>
#include <queue>
#include <cmath>
using namespace std;
int a[30],b[30];
int n;
//二叉树结构体构建
typedef struct BTree{
struct BTree *L,*R;
int data;
}BTree;
//BFS用
queue<BTree *> QQ;
//偏移量
int find(int x,int L,int R)
{
int sum = 0;
for(int i=L;i<=R;++i)
{
if(b[i] == x)
return sum;
else
++sum;
}
}
//建树 重点:区间计算
void buildBTree(int i,int j,int L,int R,BTree *root)
{
if(i>j)
{
root->data = -1;
root->L = NULL;
root->R = NULL;
return;
}
root->data = a[j];
BTree *LL = new BTree;
BTree *RR = new BTree;
root->L = LL;
root->R = RR;
int h = find(a[j],L,R);
//***区间计算***
buildBTree(i,i+h-1,L,L+h-1,LL);
buildBTree(i+h,j-1,L+h+1,R,RR);
}
//层遍历 BFS
int flag = 0;//格式控制
void BFS(BTree *root)
{
QQ.push(root);
while(QQ.size()!=0)
{
if(QQ.front()->data != -1)
{
if(flag == 0)
{
cout << QQ.front()->data;
flag = 1;
}
else
{
cout <<" " <<QQ.front()->data;
}
}
if(QQ.front()->L != NULL)
QQ.push(QQ.front()->L);
if(QQ.front()->R != NULL)
QQ.push(QQ.front()->R);
QQ.pop();
}
cout << endl;
}
int main(int argc, char** argv) {
cin >> n;
for(int i=0;i<n;++i)
cin >> a[i];
for(int i=0;i<n;++i)
cin >> b[i];
BTree *root = new BTree;
buildBTree(0,n-1,0,n-1,root);
BFS(root);
return 0;
}