zoukankan      html  css  js  c++  java
  • 1138 Postorder Traversal (25 分)前序和中序遍历转为后序

    1138 Postorder Traversal (25 分)

    Suppose that all the keys in a binary tree are distinct positive integers. Given the preorder and inorder traversal sequences, you are supposed to output the first number of the postorder 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 (≤ 50,000), the total number of nodes in the binary tree. The second line gives the preorder 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 first number of the postorder traversal sequence of the corresponding binary tree.

    Sample Input:

    7
    1 2 3 4 5 6 7
    2 3 1 5 4 7 6
    

    Sample Output:

    3
    思路:
      这个题目要求输出后序遍历第一个元素,所以只需要进行分割和输出即可。为了尽快推出递归,增加flag变量;
    为了加快速度,使用了哈希,这样在分割序列的时候不需要再进行循环。
    #include<iostream>
    #include<vector>
    #include<algorithm>
    #include<queue>
    #include<string>
    #include<map>
    #include<set>
    #include<stack>
    #include<string.h>
    #include<cstdio>
    #include<cmath>
    using namespace std;
    int pre[50001];
    int in[50001];
    map<int,int>mp;
    
    bool flag=true;
    void createTree(int pl,int pr,int il,int ir)
    {
        if(!flag)
            return;
    
        int index=mp[pre[pl]];
        int len=index-il;
        int rlen=ir-index;
        if(len>0)
            createTree(pl+1,pl+len,il,index-1);
        if(rlen>0)
            createTree(pl+len+1,pr,index+1,ir);
        if(flag)
        {
            printf("%d",pre[pl]);
           // cout<<pre[pl];
            flag=false;
            return;
        }
    }
    
    
    int main()
    {
        int n;
        scanf("%d",&n);
    
        for(int i=0; i<n; i++)
            scanf("%d",&pre[i]);
            //cin>>pre[i];
        for(int i=0; i<n; i++)
        {
            scanf("%d",&in[i]);
            mp[in[i]]=i;
        }
            //cin>>in[i];
    
        createTree(0,n-1,0,n-1);
       // non_recur(root);
        //stack<Node*> st;
        return 0;
    }
     
  • 相关阅读:
    17种高效选聘方法
    三招让你从求职者中脱颖而出(转)
    仓山有感
    同事就是同事,职场没有兄弟姐妹
    enable worker process
    央企
    关于IIS
    td
    About Application Pool
    iis 7 application pool
  • 原文地址:https://www.cnblogs.com/zhanghaijie/p/10321588.html
Copyright © 2011-2022 走看看