-
Notifications
You must be signed in to change notification settings - Fork 110
/
solution.java
90 lines (83 loc) · 2.46 KB
/
solution.java
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
import java.util.*;
public class solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner s = new Scanner(System.in);
int n = s.nextInt();
Tree tree = new Tree();
tree.value = 1;
Queue queueA = new LinkedList();
queueA.add(tree);
//while the tree has been traversed fully
while(!queueA.isEmpty())
{
Tree temp = (Tree)queueA.remove();
int value = s.nextInt();
//taking inputs and pushing them in left and right nodes respectively
if(value != -1)
{
Tree left = new Tree();
left.value = value;
temp.leftNode = left;
queueA.add(left);
}
else
temp.leftNode = null;
value = s.nextInt();
if(value != -1)
{
Tree right = new Tree();
right.value = value;
temp.rightNode = right;
queueA.add(right);
}
else
temp.rightNode = null;
}
int t = s.nextInt();
for(int i=0;i<t;i++)
{
int k = s.nextInt();
swapTree(tree,k,0,1); //to swap the elements
inorder(tree); //to traverse the tree
System.out.println();
}
}
//to traverse thru the tree
private static void inorder(Tree t)
{
if (t == null)
return;
inorder(t.leftNode);
System.out.print(t.value+" ");
inorder(t.rightNode);
}
//to swap the nodes
private static void swapTree(Tree t,int k, int cur,int mul)
{
if (t == null)
return;
cur++;
//if current value is present in swap vector
//then we swap left & right node
if(cur == (mul*k))
{
Tree temp = t.leftNode;
t.leftNode = t.rightNode;
t.rightNode = temp;
++mul;
swapTree(t.leftNode, k, cur,mul);
swapTree(t.rightNode, k, cur,mul);
}
else
{
swapTree(t.leftNode, k, cur,mul);
swapTree(t.rightNode, k, cur,mul);
}
}
}
class Tree{
int value;
Tree leftNode;
Tree rightNode;
}