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

  • 相关阅读:
    使用Kafka Connect导入/导出数据
    FastDFS :java.lang.Exception: getStoreStorage fail, errno code: 28
    Zookeeper+Kafka集群测试
    zookeeper,kafka错误
    kafka systemctl开机启动
    zookeeper systemctl开机启动
    kafka 集群安装
    kafka升级官方指导及注意事项
    centos7.7 添加nginx服务
    教你如何迅速秒杀掉:99%的海量数据处理面试题
  • 原文地址:https://www.cnblogs.com/zhuqiwei-blog/p/9560200.html
Copyright © 2011-2022 走看看