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;
    }
     
  • 相关阅读:
    python 获取在线视频时长,不下载视频
    python treeview 多线程下表格插入速度慢解决方法
    c#操作magick,magick.net
    油猴脚本-Tampermonkey-淘宝dsr过滤器(过滤非3红商品)
    python 基础小坑 0==False is True
    pyd 编译,简单命令cythonize
    python 调用Tesseract,dll模式,无需安装,绿色版
    list与set的查询效率,大量数据查询匹配,必须选set
    selenium 页面加载慢,超时的解决方案
    selenium 不打印chromedriver的日志信息
  • 原文地址:https://www.cnblogs.com/zhanghaijie/p/10321588.html
Copyright © 2011-2022 走看看