-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path749.cpp
More file actions
78 lines (70 loc) · 1.52 KB
/
749.cpp
File metadata and controls
78 lines (70 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*****************************************
* (This comment block is added by the Judge System)
* Submission ID: 71898
* Submitted at: 2018-11-19 18:22:15
*
* User ID: 539
* Username: 55211931
* Problem ID: 749
* Problem Name: Tree reconstruction
*/
#include <iostream>
using namespace std;
// A utility function to search x in arr[] of size n
int search(int arr[], int x, int n)
{
for (int i = 0; i < n; i++)
if (arr[i] == x)
return i;
return -1;
}
// Prints postorder traversal from given inorder and preorder traversals
void printPostOrder(int in[], int pre[], int n)
{
// The first element in pre[] is always root, search it
// in in[] to find left and right subtrees
int root = search(in, pre[0], n);
// If left subtree is not empty, print left subtree
if (root != 0)
{
printPostOrder(in, pre + 1, root);
cout << " ";
}
// If right subtree is not empty, print right subtree
if (root != n - 1)
{
printPostOrder(in + root + 1, pre + root + 1, n - root - 1);
cout << " ";
}
// Print root
cout << pre[0];
}
// Driver program to test above functions
int main()
{
int times;
cin >> times;
for (int i = 0;i < times;i++)
{
int in[100];
int pre[100];
int num;
cin >> num;
for (int i = 0;i < num;i++)
{
int a;
cin >> a;
pre[i] = a;
}
for (int i = 0;i < num;i++)
{
int a;
cin >> a;
in[i] = a;
}
int n = num;
printPostOrder(in, pre, n);
cout << endl;
}
return 0;
}