PAT 甲级 1020 Tree Traversals (25 分)(二叉树已知后序和中序建树求层序)

时间:2021-11-03 00:49:18
1020 Tree Traversals (25 分)

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 (≤), 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

这个推了蛮久的。。。。。不太熟练

    //左子树
if(k-l2==){
tree[root].l = -;//左子树为空
}
else{
buildTree(*root,l1,l1+k-l2-,l2,k-);
}
//右子树
if(k+>r2){
tree[root].r = -;//右子树为空
}
else{
buildTree(*root+,l1+k-l2,r1-,k+,r2);
}

AC代码:

#include<bits/stdc++.h>
using namespace std;
int post[];
int in[];
int n;
struct node{
int v;
int l;
int r;
}tree[];
queue<int>q;
void buildTree(int root,int l1,int r1,int l2,int r2){//后序,中序
//cout<<root<<" "<<l1<<"-"<<r1<<" "<<l2<<"-"<<r2<<endl;
//先找根节点
tree[root].v = post[r1];
if(l1==r1){ //只有一个节点
tree[root].l = -;
tree[root].r = -;
return;
}else{
tree[root].l = *root;
tree[root].r = *root+;
}
//找一下根在中序上的位置
int k;
for(int i=l2;i<=r2;i++){
if(in[i]==post[r1]){
k=i;//前面k-l2个数就是左子树
break;
}
}
//左子树
if(k-l2==){
tree[root].l = -;//左子树为空
}
else{
buildTree(*root,l1,l1+k-l2-,l2,k-);
}
//右子树
if(k+>r2){
tree[root].r = -;//右子树为空
}
else{
buildTree(*root+,l1+k-l2,r1-,k+,r2);
}
}
int main(){
int n;
cin>>n;
for(int i=;i<=n;i++){
cin>>post[i];
}
for(int i=;i<=n;i++){
cin>>in[i];
}
buildTree(,,n,,n);
//bfs 层序
while(!q.empty()) q.pop();
q.push();
while(!q.empty()){
node x=tree[q.front()];
q.pop();
cout<<x.v;
if(x.l!=-){
q.push(x.l);
}
if(x.r!=-){
q.push(x.r);
}
if(!q.empty()){
cout<<" ";
}
}
return ;
}