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

  • 相关阅读:
    记录一次阻塞引发的系统超时
    2015年读书清单
    循序渐进的敏捷-每日例会
    循序渐进的敏捷-交叉测试
    对一次系统上线的思考-走出“舒适区”
    单点登录(SSO)系统的总结
    对一个同事项目的思考和总结
    关于福建出差的总结
    由错误处理引发的联想-防御式编程
    关于日志记录的总结
  • 原文地址:https://www.cnblogs.com/zhuqiwei-blog/p/9560200.html
Copyright © 2011-2022 走看看