1138 Postorder Traversal (25 分)

版权声明:文章都是原创,转载请注明~~~~ https://blog.csdn.net/SourDumplings/article/details/86561746

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 (≤ 50,000), 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

 C++:

/*
 @Date    : 2018-03-07 15:48:01
 @Author  : 酸饺子 ([email protected])
 @Link    : https://github.com/SourDumplings
 @Version : $Id$
*/

/*
https://www.patest.cn/contests/pat-a-practise/1138
 */

#include <iostream>
#include <cstdio>

using namespace std;

static const int MAXN = 50001;
static int pre[MAXN], in[MAXN], post[MAXN];

void solve(int preB, int preE, int inB, int inE, int postB, int postE)
{
    if (preB == preE) return;
    int root = pre[preB];
    post[postE-1] = root;
    if (preB + 1 == preE) return;
    int lLength = preE - preB - 1;
    for (int i = inB; i != inE; ++i)
    {
        if (in[i] == root)
        {
            lLength = i - inB;
            break;
        }
    }
    solve(preB+1, preB+1+lLength, inB, inB+lLength, postB, postB+lLength);
    solve(preB+1+lLength, preE, inB+lLength+1, inE, postB+lLength, postE-1);
    return;
}

int main(int argc, char const *argv[])
{
    int N;
    scanf("%d", &N);
    for (int i = 0; i != N; ++i) scanf("%d", &pre[i]);
    for (int i = 0; i != N; ++i) scanf("%d", &in[i]);
    solve(0, N, 0, N, 0, N);
    printf("%d\n", post[0]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/SourDumplings/article/details/86561746