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;
    }
     
  • 相关阅读:
    Spark集群下的K-Means算法
    牛客:数据库SQL实战(一)查询入职最晚的员工的所有信息
    吴军《硅谷之谜》
    IntelliJ IDEA 中 右键新建(new)时,选项没有scala(java) class的解决方法和具体解释
    Gitlab跨版本升级
    Kubernetes 0-1 Pod中的livenessProbe和readinessProbe解读
    Kubernetes 0-1 了解Pod
    Kubernetes 0-1 K8S自建LoadBalancer
    Kubernetes 0-1 K8S部署coredns
    Kubernetes 0-1 二进制搭建K8S(四)部署Node
  • 原文地址:https://www.cnblogs.com/zhanghaijie/p/10321588.html
Copyright © 2011-2022 走看看