-
Notifications
You must be signed in to change notification settings - Fork 17
/
main.cpp
108 lines (94 loc) · 2.22 KB
/
main.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <queue>
#include <stack>
#include <utility>
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int data) {
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
class Tree {
private:
Node *root;
queue<Node*> build_queue;
public:
Tree(int root_data) {
root = new Node(root_data);
build_queue.push(root);
}
void LevelOrderAdd(int left_data, int right_data) {
Node *curr = build_queue.front();
if (left_data != -1) {
curr->left = new Node(left_data);
build_queue.push(curr->left);
}
if (right_data != -1) {
curr->right = new Node(right_data);
build_queue.push(curr->right);
}
build_queue.pop();
}
void InOrderPrint() {
stack<Node*> s;
Node* current = root;
do {
while (current != NULL) {
s.push(current);
current = current->left;
}
if (current == NULL && !s.empty()) {
current = s.top();
s.pop();
cout << current->data << " ";
current = current->right;
}
} while (current != NULL || !s.empty());
cout << endl;
}
void SwapOperation(int k) {
int level = 0;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
level++;
int nodes = q.size();
while (nodes--) {
Node *current = q.front();
if (current != NULL) {
if (level % k == 0) {
swap(current->left, current->right);
}
q.push(current->left);
q.push(current->right);
}
q.pop();
}
}
}
};
int main() {
int N;
cin >> N;
Tree *t = new Tree(1);
while (N--) {
int a, b;
cin >> a >> b;
t->LevelOrderAdd(a, b);
}
int T;
cin >> T;
while (T--) {
int k;
cin >> k;
t->SwapOperation(k);
t->InOrderPrint();
}
return 0;
}