-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathSwapNodes_Algo.java
77 lines (61 loc) Β· 1.99 KB
/
SwapNodes_Algo.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
package trees;
import java.util.LinkedList;
import java.util.Scanner;
public class SwapNodes_Algo {
private static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
int n = s.nextInt();
CustomTree<Integer> root = prepareTree();
root.print();
int testCases = s.nextInt();
swapNodes(root, testCases);
}
private static void swapNodes(CustomTree<Integer> root, int testCases){
while (testCases-- > 0){
int k = s.nextInt();
swapNodesKTimes(root, k, 1);
inOrder(root);
}
}
private static void swapNodes(CustomTree<Integer> root){
CustomTree<Integer> temp = root.left;
root.left = root.right;
root.right = temp;
}
private static void swapNodesKTimes(CustomTree<Integer> root, int k, int depth){
if(root == null)
return;
if(depth % k == 0)
swapNodes(root);
swapNodesKTimes(root.left, k, depth+1);
swapNodesKTimes(root.right, k, depth+1);
}
private static void inOrder(CustomTree<Integer> root){
if(root == null){
return;
}
inOrder(root.left);
System.out.print(root.data + " ");
inOrder(root.right);
System.out.println("");
}
private static CustomTree<Integer> prepareTree(){
CustomTree<Integer> root = new CustomTree<>(1);
LinkedList<CustomTree<Integer>> linkedList = new LinkedList<>();
linkedList.add(root);
while (!linkedList.isEmpty()){
CustomTree<Integer> node = linkedList.pop();
int left = s.nextInt();
int right = s.nextInt();
if(left != -1){
node.left = new CustomTree<>(left);
linkedList.add(node.left);
}
if(right != -1){
node.right = new CustomTree<>(right);
linkedList.add(node.right);
}
}
return root;
}
}