码迷,mamicode.com
首页 > 其他好文 > 详细

【PAT1138】Postorder Traversal(25)

时间:2018-03-17 00:42:20      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:contains   sep   返回   binary   ==   nta   out   can   line   

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;
}

 

【PAT1138】Postorder Traversal(25)

标签:contains   sep   返回   binary   ==   nta   out   can   line   

原文地址:https://www.cnblogs.com/xiao-gan/p/8586478.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!