-
Notifications
You must be signed in to change notification settings - Fork 79
/
SwapNodes.java
116 lines (95 loc) · 3.47 KB
/
SwapNodes.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
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
import java.util.*;
class Node {
public int data;
public int depth;
public Node left;
public Node right;
public Node(int data) {
this.data = data;
this.left = null;
this.right = null;
this.depth = 1;
}
}
public class Solution {
static ArrayList<Integer> inOrderTraverseResult;
static void inOrderTraverse(Node n) {
if (n != null){
inOrderTraverse(n.left);
inOrderTraverseResult.add(n.data + 1);
inOrderTraverse(n.right);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt(); // Number of Nodes N
in.nextLine();
// Create the binary tree
Node[] nodes = new Node[N];
for (int i = 0; i < N; i++) {
nodes[i] = new Node(i);
}
// This one will be handy for the swapping below
Map<Integer, ArrayList<Integer>> depthMap = new HashMap<Integer, ArrayList<Integer>>();
String nextNode;
String[] nextNodeSplit;
int left;
int right;
for (int i = 0; i < N; i++) {
nextNode = in.nextLine();
nextNodeSplit = nextNode.split(" ");
left = Integer.parseInt(nextNodeSplit[0]);
right = Integer.parseInt(nextNodeSplit[1]);
if (left != -1) {
nodes[i].left = nodes[left - 1];
nodes[i].left.depth = nodes[i].depth + 1;
}
if (right != -1) {
nodes[i].right = nodes[right - 1];
nodes[i].right.depth = nodes[i].depth + 1;
}
if (!depthMap.containsKey(nodes[i].depth)) {
depthMap.put(nodes[i].depth, new ArrayList<Integer>());
}
depthMap.get(nodes[i].depth).add(i);
}
// Now we will read the `swaps they want us to do` data
int T = in.nextInt(); // Number of Test swaps
in.nextLine();
int K;
for (int i = 0; i < T; i++) {
K = in.nextInt();
// Get the multiples by 2 on K to get the depth h
for (int h = K; h <= N; h += K) {
if (!depthMap.containsKey(h)) break;
// Iterate over the indexes on that depth
int nodeIdx, nodeLeftIdx, nodeRightIdx;
for (int n = 0; n < depthMap.get(h).size(); n++) {
nodeIdx = depthMap.get(h).get(n);
if (nodes[nodeIdx].left != null) {
nodeLeftIdx = nodes[nodeIdx].left.data;
} else {
nodeLeftIdx = 0;
}
if (nodes[nodeIdx].right != null) {
nodeRightIdx = nodes[nodeIdx].right.data;
} else {
nodeRightIdx = 0;
}
nodes[nodeIdx].left = nodeRightIdx != 0 ? nodes[nodeRightIdx] : null;
nodes[nodeIdx].right = nodeLeftIdx != 0 ? nodes[nodeLeftIdx] : null;
}
}
inOrderTraverseResult = new ArrayList<Integer>();
inOrderTraverse(nodes[0]);
String result = "";
for (int tr = 0; tr < inOrderTraverseResult.size(); tr++) {
if (tr != 0) {
result += " ";
}
result += inOrderTraverseResult.get(tr);
}
System.out.println(result);
}
}
}