1. 程式人生 > >PAT-1138. Postorder Traversal (25)

PAT-1138. Postorder Traversal (25)

cati end href lin ref cas oid strong %d

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\n", 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;
}

PAT-1138. Postorder Traversal (25)