-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path749.cpp
More file actions
55 lines (49 loc) · 990 Bytes
/
Copy path749.cpp
File metadata and controls
55 lines (49 loc) · 990 Bytes
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
#include<iostream>
#include<cstring>
using namespace std;
int n;
int* preorder;
int* inorder;
bool printed;
void ana(int treePos, int preLeft, int preRight, int inLeft, int inRight) {
int find;
for (int i = inLeft; i <= inRight; i++) {
if (preorder[preLeft] == inorder[i]) {
find = i;
break;
}
}
if (find > inLeft) {
ana(treePos * 2 + 1, preLeft + 1, preLeft + find - inLeft, inLeft, find - 1);
}
if (find < inRight) {
ana(treePos * 2 + 2, preLeft + find - inLeft + 1, preRight, find + 1, inRight);
}
if (printed) {
cout << " ";
}
else {
printed = true;
}
cout << preorder[preLeft];
}
int main() {
int caseNum;
cin >> caseNum;
for (int c = 0; c < caseNum; c++) {
cin >> n;
preorder = new int[n];
inorder = new int[n];
for (int i = 0; i < n; i++) {
cin >> preorder[i];
}
for (int i = 0; i < n; i++) {
cin >> inorder[i];
}
printed = false;
ana(0, 0, n - 1, 0, n - 1);
cout << endl;
delete[] preorder;
delete[] inorder;
}
}