题目描述 |
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
解题思路 |
题目大意
已知树的后序和中序排列,按树的层次进行遍历输出
思路
关于树的一道基础题,在已知后序和中序的情况下进行建树,然后用广搜进行层次遍历.
当然可以不用这个方案,直接由后序和中序得出先序结果,再此基础上,将先序遍历的结果存放至数组中,并按下标排列成层次遍历,如某节点下标为k,则其左子节点下标为2k,右子节点下标为2k+1.具体可点击代码链接进行查看
代码设计 |
//AC代码
//zhicheng
#include<cstdio>
#include<iostream>
#include<queue>
using namespace std;
// zhicheng
//August 15,2018
const int maxn=31;
int in_order[maxn],post_order[maxn],rtree[maxn],ltree[maxn];
int n;
int build(int l1,int r1,int l2,int r2)
{//建树
if(l1>r1) return 0;
int node=post_order[r2];
int p=l1;
while(in_order[p]!=node) p++;
ltree[node]=build(l1,p-1,l2,l2+p-l1-1);
rtree[node]=build(p+1,r1,l2+p-l1,r2-1);
return node;
}
void bfs(int root)
{//广搜进行层次遍历
queue<int> q;
q.push(root);
while(!q.empty())
{
int u=q.front();q.pop();
if(u==root) printf("%d",u);
else printf(" %d",u);
if(ltree[u]) q.push(ltree[u]);
if(rtree[u]) q.push(rtree[u]);
}
}
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]);
int root=build(0,n-1,0,n-1);
bfs(root);
printf("\n");
return 0;
}
有关PAT (Basic Level) 的更多内容可以关注 ——> PAT-B题解
有关PAT (Advanced Level) 的更多内容可以关注 ——> PAT-A题解