-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path1020.cpp
More file actions
40 lines (36 loc) · 983 Bytes
/
1020.cpp
File metadata and controls
40 lines (36 loc) · 983 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
#include <iostream>
#include <queue>
using namespace std;
struct TreeNode {
int key;
TreeNode *left;
TreeNode *right;
};
TreeNode *create_tree(int *post, int *in, int len) {
if (len <= 0) return nullptr;
int i = 0;
TreeNode *root = new TreeNode{post[len - 1], nullptr, nullptr};
while (i < len && in[i] != root->key) i++;
root->left = create_tree(post, in, i);
root->right = create_tree(post + i, in + i + 1, len - i - 1);
return root;
}
void bfs(TreeNode *root) {
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode *temp = q.front(); q.pop();
if (temp->left) q.push(temp->left);
if (temp->right) q.push(temp->right);
cout << temp->key << (!q.empty() ? ' ' : '\n');
}
}
int main() {
int n;
cin >> n;
int post[n], in[n];
for (int i = 0; i < n; i++) cin >> post[i];
for (int i = 0; i < n; i++) cin >> in[i];
bfs(create_tree(post, in, n));
return 0;
}