题目
https://www.patest.cn/contests/pat-a-practise/1020
题意:给定二叉树的后序、中序遍历结果,输出其层次遍历结果
解题思路
首先重建树,关于利用含中序的两种序列构建这棵二叉树,详见之前的博客二叉树遍历(已知前中序求后序),最后根据这棵树的层次做输出,一遍BFS就可以解决。
AC代码
#include <iostream>
#include <queue>
#include <cstdlib>
using namespace std;
const int maxn =
35;
int n, posOrder[maxn], midOrder[maxn];
typedef struct node
{
int value;
node *left, *right;
}NODE;
NODE* BuildTree(
int s1,
int e1,
int s2,
int e2)
{
NODE* newnode = (NODE*)
malloc(
sizeof(NODE));
newnode->value = posOrder[e1];
newnode->left = newnode->right = NULL;
int cmp = posOrder[e1], rootIndex = -
1;
for (
int i = s2; i<=e2; ++i)
{
if (midOrder[i] == cmp)
{
rootIndex = i;
break;
}
}
if (rootIndex != e2)
newnode->right = BuildTree(e1-(e2-rootIndex), e1-
1, rootIndex+
1, e2);
if (rootIndex != s2)
newnode->left = BuildTree(s1, e1-(e2-rootIndex)-
1, s2, rootIndex-
1);
return newnode;
}
void BFS(NODE *root)
{
vector<int> res;
queue<NODE> q;
NODE tmp;
q.push(*root);
while(!q.empty())
{
int sz = q.size();
for (
int i =
0; i<sz; ++i)
{
tmp = q.front();
q.pop();
res.push_back(tmp.value);
if (tmp.left != NULL)
q.push(*tmp.left);
if (tmp.right != NULL)
q.push(*tmp.right);
}
}
for (
int i =
0; i < res.size(); ++i)
{
cout << res[i];
if (i != res.size()-
1)
cout <<
' ';
else cout << endl;
}
}
int main()
{
cin >> n;
for (
int i =
0; i<n; ++i)
cin >> posOrder[i];
for (
int i =
0; i<n; ++i)
cin >> midOrder[i];
NODE* root = BuildTree(
0, n-
1,
0, n-
1);
BFS(root);
return 0;
}