PAT1138Postorder Traversal(25)

Posted xiao-gan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT1138Postorder Traversal(25)相关的知识,希望对你有一定的参考价值。

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


坑点:
1. 唯一要注意的是递归太深,会导致堆栈溢出,所以要控制递归返回条件
#include <iostream>
#include <string>
#include <string.h>
#include <map>
#include <set>
#include <list>
#include <vector>
#include <deque>
#include <unordered_set>
#include <algorithm>
#include <unordered_map>
#include <stack>
#include <cstdio>
using namespace std;

int preArr[50001];
int inArr[50001];
int n;
int preIndex = 1;
int flag = -1;

int findHeadIndex(int head,int left,int right)
{
    for (int i = left;i <= right;i++)
        if (inArr[i] == head)
            return i;
}

void find(int left, int right)
{
    if (flag >-1 ||left > right)
        return;
    if (left == right && flag == -1)
    {
        cout << inArr[right];
        flag++;
        return;
    }
    int head = findHeadIndex(preArr[preIndex++], left, right);
    find(left, head - 1);
    find(head + 1, right);
}

int main()
{
    cin >> n;
    for (int i = 1;i <= n;i++)
    {
        scanf("%d", &preArr[i]);
    }
    for (int i = 1;i <= n;i++)
    {
        scanf("%d", &inArr[i]);
    }
    find(1, n);
    return 0;
}

 

以上是关于PAT1138Postorder Traversal(25)的主要内容,如果未能解决你的问题,请参考以下文章

PAT1138Postorder Traversal(25)

1138. Postorder Traversal (25)

1138 Postorder Traversal (25)

1138 Postorder Traversal(先序+中序=二叉树)

1138 Postorder Traversal (25 分)难度: 一般 / 知识点: 建树

145. Binary Tree Postorder Traversal