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
题意:给出一个数字n表示一个序列序列一共有n个数字。下面两行分别给出一棵 树的后序遍历和中序遍历,让你输出层次遍历。
思路:后序遍历的最后一个节点一定是根,我们在中序遍历中找到找到这个节点,在中序遍历左侧的数都是左子树,右侧的都是右子树。左子树的根节点对应于后序遍历的endd-(右子树个数)。而这个右子树的个数是可以在中序遍历中计算出来的。这样,我们就可以得到一个前序遍历。靠着递归得到前序遍历的过程,我们记录他的深度就可以得到层次遍历了。直接开一个vector,按深度输出数据就好了。
#include<bits/stdc++.h>
#pragma GCC optimize(2)
#define MAXN 50
#define maxnode 1000005
#define sigma_size 26
#define md 12345678
#define INF 0x3f3f3f3f
using namespace std;
int post_order[MAXN],in_order[MAXN];
int n,maxn;
vector<int> pp[MAXN];
void pre_order(int root,int start,int endd,int deep) //根据后序和中序输出前序
{
if(start>endd)
return ;
int i=start;
while(i<endd&&in_order[i]!=post_order[root])
i++;
//printf("%d\n",post_order[root]);
maxn=max(maxn,deep);
pp[deep].push_back(post_order[root]);
pre_order(root-1-endd+i,start,i-1,deep+1);
pre_order(root-1,i+1,endd,deep+1);
}
int main()
{
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&post_order[i]);
for(int i=0;i<n;i++)
scanf("%d",&in_order[i]);
pre_order(n-1,0,n-1,0);
bool first=false;
for(int i=0;i<=maxn;i++)
{
for(int j=0;j<pp[i].size();j++)
{
if(first)
printf(" ");
printf("%d",pp[i][j]),first=true;
}
}
return 0;
}