1. 程式人生 > >【PAT1138】Postorder Traversal(25)

【PAT1138】Postorder Traversal(25)

log dex ins preorder head using rst cas span

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)