forked from richenyunqi/CCF-CSP-and-PAT-solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1020. Tree Traversals.cpp
47 lines (47 loc) · 1.21 KB
/
1020. Tree Traversals.cpp
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
#include <bits/stdc++.h>
using namespace std;
using gg = long long;
struct BTNode {
gg val;
BTNode *left, *right;
BTNode(gg v, BTNode* l = nullptr, BTNode* r = nullptr) : val(v) {}
};
BTNode* buildTree(vector<gg>& post, vector<gg>& in, gg r, gg left, gg right) {
if (left > right)
return nullptr;
gg i = find(in.begin(), in.end(), post[r]) - in.begin();
auto root = new BTNode(post[r]);
root->left = buildTree(post, in, r - 1 - (right - i), left, i - 1);
root->right = buildTree(post, in, r - 1, i + 1, right);
return root;
}
void levelOrder(BTNode* root) {
queue<BTNode*> q;
q.push(root);
bool space = false;
while (not q.empty()) {
auto t = q.front();
q.pop();
cout << (space ? " " : "") << t->val;
if (t->left)
q.push(t->left);
if (t->right)
q.push(t->right);
space = true;
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
gg ni;
cin >> ni;
vector<gg> post(ni), in(ni);
for (gg i = 0; i < ni; ++i) {
cin >> post[i];
}
for (gg i = 0; i < ni; ++i) {
cin >> in[i];
}
levelOrder(buildTree(post, in, ni - 1, 0, ni - 1));
return 0;
}