PAT 1020. Tree Traversals

Posted A-Little-Nut

tags:

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

PAT 1020. Tree Traversals

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

分析

首先后序遍历的最后一个数必定是根节点,然后在中序遍历中找的根节点,根节点前面的是该节点的左子树,后面的是右子树,再对左右子树递归的调用前面的步骤;

代码如下

#include<iostream>
#include<vector>
using namespace std;
vector<int> post,in,level(100000,-1);
void pre(int root,int s,int e,int index){
    if(s>e) return ;
    level[index]=post[root];
    int i=s;
    for(;i<=e;i++) 
    if(in[i]==post[root]) break;
    pre(root-(e-i+1),s,i-1,index*2+1);
    pre(root-1,i+1,e,index*2+2);
} 
int main(){
    int N; cin>>N;
    post.resize(N); in.resize(N);
    for(int i=0;i<N;i++) cin>>post[i];
    for(int i=0;i<N;i++) cin>>in[i];
    pre(N-1,0,N-1,0);
    for(int i=0;i<level.size();i++)
    if(level[i]!=-1)
    i>0?cout<<" "<<level[i]:cout<<level[i];
    return 0;
}

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

PAT1020: Tree Traversals

PAT 1020 Tree Traversals (25)

PAT_A1020#Tree Traversals

PAT 甲级 1020 Tree Traversals

PAT1020 Tree Traversals (25)(25 分)

PAT Advanced 1020 Tree Traversals (25分)