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;
    }
  • 相关阅读:
    转:.net面试题及答案(一)
    高兴!
    游标中LOCAL的意思
    九度 1333
    在进程槽中为进程分配一个空闲位置并分配一个进程号
    USACO Section 1.2 Milking Cows
    九度 1334
    USACO Section 1.3 Mixing Milk
    USACO Section 1.3 Calf Flac
    USACO Section 1.3 Prime Cryptarithm
  • 原文地址:https://www.cnblogs.com/ACMessi/p/8492585.html
Copyright © 2011-2022 走看看