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

  • 相关阅读:
    [UE4]创建对象的的几种姿势(C++)
    [UE4]IES光源概述文件
    [UE4]C++ STL总结
    [UE4]C++中引用(&)的用法和应用实例
    [UE4]单映射:TMap容器,字典表
    [UE4]集合:TSet容器
    [UE4]动态数组:TArray容器
    [UE4] 虚幻4学习---UE4中的字符串转换
    [UE4]使用PlayerController获取鼠标点击时的坐标
    [UE4]C 语言动态数组
  • 原文地址:https://www.cnblogs.com/zhuqiwei-blog/p/9560200.html
Copyright © 2011-2022 走看看