zoukankan      html  css  js  c++  java
  • A1138. Postorder Traversal

    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

    #include<cstdio>
    #include<iostream>
    using namespace std;
    typedef struct NODE{
        struct NODE* lchild, *rchild;
        int data;
    }node;
    int pre[60000], in[60000];
    node* create(int preL, int preR, int inL, int inR){
        if(preL > preR)
            return NULL;
        node *root = new node;
        root->data = pre[preL];
        int mid;
        for(int i = inL; i <= inR; i++){
            if(in[i] == root->data){
                mid = i;
                break;
            }
        }
        int len = mid - inL;
        root->lchild = create(preL + 1, preL + len, inL, mid - 1);
        root->rchild = create(preL + len + 1, preR, mid + 1, inR);
        return root;
    }
    int N;
    int cnt = 0;
    void postOrder(node* root){
        if(root == NULL)
            return;
        if(cnt != 0)
            return;
        postOrder(root->lchild);
        postOrder(root->rchild);
        if(cnt == 0){
            printf("%d", root->data);
            cnt++;
        }
    }
    int main(){
        scanf("%d", &N);
        for(int i = 0; i < N; i++){
            scanf("%d", &pre[i]);
        }
        for(int i = 0; i < N; i++){
            scanf("%d", &in[i]);
        }
        node* root = create(0, N - 1, 0, N - 1);
        postOrder(root);
        cin >> N;
        return 0;
    }
    View Code

    总结:

    1、题意:由先序和中序序列建树,再输出后序遍历的第一个节点。

  • 相关阅读:
    安装mysql时 Write configuration file 错误
    Statement和PreparedStatement之间的区别
    Matlab 的fspecial函数用法
    MySql 5.1 在线中文参考手册
    Rational License Key Error 的解决办法
    Admin5论坛营销插件
    actcms发布模块,如何使用?
    博客大巴(BlogBus)
    淘宝评论采集,因为是原创
    忍者X3又添新成员 IIS6批量建站
  • 原文地址:https://www.cnblogs.com/zhuqiwei-blog/p/9560200.html
Copyright © 2011-2022 走看看