PAT A1138 Postorder Traversal (25 minutes) Binary Tree Traversal

Posted by elenev on Tue, 01 Oct 2019 18:36:11 +0200

Main idea of the title: Give the pre-order and middle-order sequence of the binary tree (<=50000 nodes), and the first node of the output traversal after the output.

Because there are too many nodes, it will be time-out if the tree is built first and then traversed. Therefore, we should consider the characteristics of sequential traversal. The first node of sequential traversal output is the first leaf node encountered in the process of sequential traversal, that is, the first node with empty children in the process of building a tree. Therefore, in the process of building a tree, we can directly end the process of building a tree and output this value when we encounter a node with empty left and right children. To avoid timeouts, map is used to store the values and corresponding subscripts of the ordered sequence, and it is not necessary to traverse the ordered sequence to obtain the subscripts of the elements.

AC Code:

#include <iostream>
#include <vector>
#include <cstdio>
#include <map>
using namespace std;

vector<int> pre;
map<int, int> in;
struct Node
{
    int data;
    Node* left;
    Node* right;
    Node(int data):data(data), left(NULL), right(NULL){};
};

void createFromPreIn(Node* &node, int prel, int prer, int inl, int inr, bool &flag, int &ret)
{
    if(prel > prer || flag) return;
    if(node == NULL) node = new Node(pre[prel]);
    int index = in[pre[prel]];
    int leftNum = index - inl;
    int rightNum = inr - index;
    if(leftNum == 0 && rightNum == 0)
    {
        flag = true;
        ret = pre[prel];
        return;
    }
    createFromPreIn(node->left, prel + 1, prel + leftNum, inl, index - 1, flag, ret);
    createFromPreIn(node->right, prel + leftNum + 1, prer, index + 1, inr, flag, ret);
}

int main()
{
    int N;
    scanf("%d", &N);
    pre.resize(N);
    for (int i = 0; i < N; ++i)
    {
        scanf("%d", &pre[i]);
    }
    for (int i = 0; i < N; ++i)
    {
        int data;
        scanf("%d", &data);
        in[data] = i;
    }
    Node* root = NULL;
    bool flag = false;
    int ret = 0;
    createFromPreIn(root, 0, N-1, 0, N-1, flag, ret);
    printf("%d", ret);
    return 0;
}