zoukankan      html  css  js  c++  java
  • PAT-1138. Postorder Traversal (25)

    1138. Postorder Traversal (25)

    时间限制
    600 ms
    内存限制
    65536 kB
    代码长度限制
    16000 B
    判题程序
    Standard
    作者
    CHEN, Yue

    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 (<=50000), 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 <bits/stdc++.h>
    
    using namespace std;
    
    int N, M, K;
    int pre[50004], in[50004];
    
    struct Node {
        Node* left;
        Node* right;
        int value;
    };
    
    Node* buildTree(int* a, int* b, int len) {
        Node* node = new Node();
        node->value = a[0];
        //cout<< node->value<< endl;
        if(len == 0) return NULL;
        if(len == 1) return node;
        int k = 0;
        for(int i = 0; i < len; i++) {
            if(b[i] == a[0]) {
                k = i;
                break;
            }
        }
        node->left = buildTree(a+1, b, k);
        node->right = buildTree(a+k+1, b+k+1, len-k-1);
        return node;
    }
    
    int flag = 0;
    
    void postOrder(Node* node) {
        if(node->left) {
            postOrder(node->left);
        }
        if(node->right) {
            postOrder(node->right);
        }
        if(flag == 0){
            printf("%d
    ", node->value);
            flag++;
        }
    }
    
    int main()
    {
        cin>> N;
        for(int i = 0; i < N; i++) {
            scanf("%d", &pre[i]);
        }
        for(int i = 0; i < N; i++) {
            scanf("%d", &in[i]);
        }
        Node* head = buildTree(pre, in, N);
        postOrder(head);
        return 0;
    }
  • 相关阅读:
    javascript HTML DOM
    js 同步异步阻塞非阻塞非原创
    端口规范
    SASS用法指南
    整合js,css文件
    HTTP状态码大全
    控制移动端页面的缩放(meta)
    移动端最小以及最大的宽度
    H5手机端关注的问题
    javascript高级编程3第三章:基本概念 本章内容 语法 数据类型 流控制语句 函数
  • 原文地址:https://www.cnblogs.com/ACMessi/p/8492585.html
Copyright © 2011-2022 走看看