PAT Advanced 1020 Tree Traversals (25分)

Posted littlepage

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT Advanced 1020 Tree Traversals (25分)相关的知识,希望对你有一定的参考价值。

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

这道题考察了中序后序建树,然后层序遍历。

实际上,我们在进行递归的时候进行建一个索引,之后用map进行保存即可

#include <iostream>
#include <map>
using namespace std;
int N;
int post[100],in[100];
map<int,int> m;
/** root是post的索引,而start和_end都是为了确定in的索引*/
void pre(int root,int start,int _end,int index){
    if(start>_end) return;
    int i=start;
    while(i<_end&&in[i]!=post[root]) i++;
    m[index]=post[root];
    pre(root-(_end-i)-1,start,i-1,index*2);
    pre(root-1,i+1,_end,index*2+1);
}
int main(){
    cin>>N;
    for(int i=1;i<=N;i++) cin>>post[i];
    for(int i=1;i<=N;i++) cin>>in[i];
    pre(N,1,N,1);
    bool start = true;
    for(auto it=m.begin();it!=m.end();it++)
        if(start) start=false,printf("%d",it->second);
        else printf(" %d",it->second);
    system("pause");
    return 0;
}

以上是关于PAT Advanced 1020 Tree Traversals (25分)的主要内容,如果未能解决你的问题,请参考以下文章

PAT 1020. Tree Traversals

PAT 1020 Tree Traversals

PAT1020: Tree Traversals

PAT_A1020#Tree Traversals

PAT 1020 Tree Traversals (25)

PAT1020 Tree Traversals (25)(25 分)