zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    计算机网络【10】—— Cookie与Session
    计算机网络【9】—— HTTP1.0和HTTP1.1的区别及常见状态码
    计算机网络【8】—— Get和Post请求的区别
    计算机网络【7】—— TCP的精髓
    数据库事务的四大特性以及事务的隔离级别
    JavaWeb基础【1】—— Tomcat
    Get current time and date on Android
    Converting Storyboard from iPhone to iPad
    iPhone OS 开发
    (译)iOS Code Signing: 解惑
  • 原文地址:https://www.cnblogs.com/littlepage/p/12219182.html
Copyright © 2011-2022 走看看