-
Notifications
You must be signed in to change notification settings - Fork 2
/
1102.cpp
73 lines (65 loc) · 1.61 KB
/
1102.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
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
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct TreeNode {
int key;
TreeNode *left = nullptr;
TreeNode *right = nullptr;
};
void invert(TreeNode *node) {
if (node == nullptr) return;
invert(node->left);
invert(node->right);
swap(node->left, node->right);
}
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');
}
}
void print(TreeNode *node) {
static bool flag = false;
if (flag) cout << ' ';
cout << node->key;
flag = true;
}
void in_order(TreeNode *node) {
if (node == nullptr) return;
in_order(node->left);
print(node);
in_order(node->right);
}
TreeNode* find_root(vector<TreeNode> &nodes) {
const int n = nodes.size();
vector<bool> is_root(n, true);
for (auto node : nodes) {
if (node.left ) is_root[node.left ->key] = false;
if (node.right) is_root[node.right->key] = false;
}
for (int i = 0; i < n; i++)
if (is_root[i]) return &nodes[i];
return nullptr;
}
int main() {
int n;
cin >> n;
vector<TreeNode> nodes(n);
for (int i = 0; i < n; i++) {
nodes[i].key = i;
string l, r;
cin >> l >> r;
if (l != "-") nodes[i].left = &nodes[stoi(l)];
if (r != "-") nodes[i].right = &nodes[stoi(r)];
}
TreeNode *root = find_root(nodes);
invert(root);
bfs(root);
in_order(root);
return 0;
}