Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
题目大意:
英语太菜了,看半天没看出来是给你二叉树的后序遍历和中序遍历,让你求层序遍历(一开始还以为是求前序) =_=。
解题思路:
看懂题目后这题就不难了,只要把树建出来就行了。
我们可以利用后序遍历和中序遍历的特点(后序最后一个一定是根节点,由这个根节点可以在中序得到左子树的节点数目)递归建树。
建完树用 BFS 广搜层序即可。
AC代码:
//输入后序和中序得层序
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<vector>
#include<queue>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
const int N=1e3+10;
int n;
int postorder[N],inorder[N];//后序和中序
vector<int> v;
struct tree
{
int left,right;
}tire[N];
int build(int l1,int r1,int l2,int r2)//后序-中序
{
if(l2>r2)
return 0;
int root=postorder[r1];//由后序得到根节点
int p=l2;
while(inorder[p]!=root)//在中序中得到左子树的数目
{
p++;
}
int ans=p-l2-1;
tire[root].left=build(l1,l1+ans,l2,p-1);//左子树递归找左子树根节点
tire[root].right=build(l1+ans+1,r1-1,p+1,r2);//右子树递归
return root;
}
void bfs(int x)//层序广搜
{
queue<int> q;
q.push(x);
while(!q.empty())
{
int tmp=q.front();
q.pop();
v.push_back(tmp);
if(tire[tmp].left!=0)
q.push(tire[tmp].left);
if(tire[tmp].right!=0)
q.push(tire[tmp].right);
}
}
int main()
{
v.clear();
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&postorder[i]);
}
for(int i=0;i<n;i++)
{
scanf("%d",&inorder[i]);
}
int root=postorder[n-1];
build(0,n-1,0,n-1);
bfs(root);
int len=v.size();
for(int i=0;i<len;i++)
{
printf("%d%c",v[i],i==len-1?'\n':' ');
}
return 0;
}