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、题意:由先序和中序序列建树,再输出后序遍历的第一个节点。

  • 相关阅读:
    Poj 3177 Redundant Paths (双连通分支+节点统计)
    Uva 796 Critical Links (割边+排序)
    Lightoj 1020
    Flip Game---poj1753(状压+bfs)
    Best Cow Line---poj3617(贪心)
    滑雪---poj1088(动态规划+记忆化搜索)
    King's Quest---poj1904(连通图缩点)
    Steady Cow Assignment---poj3189(多重匹配+二分)
    B. Berland National Library---cf567B(set|模拟)
    HDU Today---hdu2112(最短路-_-坑在是无向图)
  • 原文地址:https://www.cnblogs.com/zhuqiwei-blog/p/9560200.html
Copyright © 2011-2022 走看看