• 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;
    }
  • 相关阅读:
    Django----路由控制
    Django-ORM的使用
    Django-ORM框架
    Django对数据库表的操作
    Python操作mysql
    [mysql]linux mysql 基础命令操作
    [mysql]linux mysql 读写分离
    [mysql]linux mysql 主从复制
    [mysql 1]linux mysal 安装
    [mysql]linux mysal 安装
  • 原文地址:https://www.cnblogs.com/ACMessi/p/8492585.html
Copyright © 2020-2023  润新知