-
Notifications
You must be signed in to change notification settings - Fork 0
/
SwapNodes.cpp
executable file
·142 lines (118 loc) · 2.24 KB
/
SwapNodes.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/*Problem Statement at : https://www.hackerrank.com/challenges/swap-nodes-algo */
#include <queue>
#include <iostream>
using namespace std;
struct node
{
int data;
struct node *left;
struct node *right;
node(int n)
{
data = n;
left = NULL;
right = NULL;
}
};
void InOrder(struct node *root)
{
if(! root)
return;
InOrder(root->left);
cout<<root->data<<' ';
InOrder(root->right);
}
void swapSubtreesOfLevel(node *root,int k)
{
if(! root)
return;
queue<node *> Q;
Q.push(root);
Q.push(NULL);
int level = 1;
while(! Q.empty())
{
node *tmp = Q.front();
Q.pop();
if(tmp == NULL)
{
if(! Q.empty())
{
Q.push(NULL);
}
level++;
}
else
{
if(level == k)
{
node *sw = tmp->left;
tmp->left = tmp->right;
tmp->right = sw;
}
if(tmp->left)
Q.push(tmp->left);
if(tmp->right)
Q.push(tmp->right);
}
}
}
int main() {
int N;
cin>>N;
node *root = NULL;
queue<node *> Q;
int level = 1;
if(N > 0)
{
root = new node(1);
Q.push(root);
Q.push(NULL);
}
while((N > 0) && ( ! Q.empty()))
{
node *tmp = Q.front();
Q.pop();
if(tmp == NULL)
{
if(!Q.empty())
Q.push(NULL);
level++;
}
else
{
int a,b;
cin>>a>>b;
if(a != -1)
{
tmp->left = new node(a);
Q.push(tmp->left);
}
if(b != -1)
{
tmp->right = new node(b);
Q.push(tmp->right);
}
N--;
}
}
int T;
cin>>T;
while(T > 0)
{
int k;
cin>>k;
int itr = 2;
int lvl = k;
while(lvl <= level )
{
swapSubtreesOfLevel(root,lvl);
lvl = itr * k;
itr++;
}
InOrder(root);
cout<<endl;
T--;
}
return 0;
}