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;
    }
     
  • 相关阅读:
    后台接受ajax传递值的实例代码
    如何动态添加和删除一个div
    模拟实现兼容低版本IE浏览器的原生bind()函数功能
    javascript当文本框获得焦点设置边框
    js实现未知宽高的元素在指定元素中垂直水平居中
    产品图片无缝水平滚动效果代码
    jQuery实现的鼠标滑过切换图片代码实例
    如何实现在密码框如出现提示语
    JS 中 Class
    从网页源代码来找flash播放器腾讯视频源地址
  • 原文地址:https://www.cnblogs.com/zhanghaijie/p/10321588.html
Copyright © 2011-2022 走看看